PHP 7.1: Void return types in functions and methods

PHP 7.1: Void return types in functions and methods

Void return types in PHP 7.1

Since PHP 7.1 we can start to see a real good progress with void return types. We can now specify a null type of returned value from a function. Sometimes we may want to specify the function which should not return any value to the user.

Functions declared with void as their return type can either omit their return statement altogether, or use an empty return statement. NULL is not a valid return value for a void function. Attempting to use a void function’s return value simply evaluates to NULL, with no warnings emitted.

Take a look at some potential fatal errors throws if you are suing PHP 7.1:

function should_return_nothing(): void {
    return 1; // Fatal error: A void function must not return a value
}

public function returns_null(): void {
    return null; // Fatal error: A void function must not return a value
}

And here are some valid use cases for using a void in function or method:

function lacks_return(): void {
    // valid
}

public function returns_nothing(): void {
    return; // valid
}

Reference

PHP 7 News & Updates v7.0 - 7.4 - Book coverPHP 7 News & Updates v7.0 – 7.4 Book https://www.amazon.com/PHP-News-Updates-v7-0-7-4/dp/1727202481/

Rate this artcile
[Total: 1 Average: 5]
Please follow and like us:

1 thought on “PHP 7.1: Void return types in functions and methods

Leave a Comment