I recently started learning PHP and since I'm used to strongly typed languages (C++, Java) I would really prefer to make use of type hinting and return type declarations. However when I'm trying to use return type declaration for primitives I get a fatal error, stating that my function does not return the correct type.
Here is a code example:
<?php
namespace Foo;
class Bar {
public function bar() : boolean {
return true;
}
}
$bar = new Bar();
$bar->bar();
?>
This will cause a fatal error, stating that Bar::bar does not return a value of Foo\boolean type. So I tried resorting to the global namespace by changing the function prototype to:
public function bar() : \boolean
But then I got a fatal error stating that my function does not return a value of type boolean. I guess PHP is looking for a type called boolean in the global namespace and not for the primitive type. Great, so how am I supposed to indicate that I want my function to return a value of the primitive type boolean?
The type hint for a Boolean value is actually bool
. Try this:
<?php
namespace Foo;
class Bar {
public function bar() : bool {
return true;
}
}
$bar = new Bar();
$bar->bar();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With