PHP return type
Since this question still comes up in search engine results, here is an up-to-date answer:
PHP 7 actually introduced proper return types for functions / methods as per this RFC.
Here is the example from the manual linked above:
function sum($a, $b): float {
return $a + $b;
}
Or, in a more general notation:
function function_name(): return_type {
// some code
return $var // Has to be of type `return_type`
}
If the returned variable or value does not match the return type, PHP will implicitly convert it to that type. Alternatively, you can enable strict typing for the file via declare(strict_types=1);
, in which case a type mismatch will lead to a TypeError Exception.
Easy as that. However, remember that you need to make sure that PHP 7 is available on both, your development and production server.
It's not possible to explicitly define the return type at the method/function level. As specified, you can cast in the return, so for example ...
return (bool)$value;
Alternatively, you can add a comment in phpDoc syntax, and many IDEs will pick up the type from a type completion perspective.
/**
* example of basic @return usage
* @return myObject
*/
function fred()
{
return new myObject();
}
As per this page : http://php.net/manual/en/language.types.type-juggling.php
You can try doing,
return (boolean) $value;
Now PHP offer return type declaration from PHP 7. I have explained how to use return type in PHP