I found that someone writes code like this:
class Abc
{
public function foo(int $bar) : string {}
}
What does :
mean in a function? What's the effect of changing string
to bool
or array
or int
?
I just don't understand why we need : xxx
, and when to use it?
That is the return type declaration, a feature introduced with PHP 7.
The type that you see after the colon, is the type that will be returned with the function.
There are 2 options:
By default the returned value will be converted to the type that needs to be returned.
In your case it will always be converted to a string.
If strict typing is enabled (by declare(strict_types=1);
), the output needs to be a string, or it will throw a TypeError.
Either way: as a developer you are always sure that the return type is a string in this case.
It is not obligatory to define the return type, so you can leave it if you don't want it. The return type in that case can be anything.
It's declares the return type for the function.
function foo (int $bar) : string { }
The int $bar
part says that the $bar parameter must be an integer, and the : string
part says the function will return a string. If the function is not passed an int or does not return a string, a TypeError will be thrown.
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