2
I’ve seen it done over and over again:
interface LoggerAwareInterface
{
public function setLogger(LoggerInterface $logger);
}
Put a parameter before the variable, in which case what it would be and what it does?
2
I’ve seen it done over and over again:
interface LoggerAwareInterface
{
public function setLogger(LoggerInterface $logger);
}
Put a parameter before the variable, in which case what it would be and what it does?
7
This is not parameter, the parameter is the $logger
. What comes before, the LoggerInterface
, is the type of the parameter. That is, PHP will only accept a call to this method if an argument of this type is passed. So the method is to have a signing that is fundamental in interfaces.
It seems a little strange in PHP because it is a language of dynamic typing, but it is common in other languages and for some tasks in PHP this is useful to make the code more robust. Because of its dynamic characteristic, robustness will only occur with tests, since instead of picking up in compilation the error will only be discovered at runtime by launching an exception.
A type can be defined by classes, or interfaces, as in the example, or traits besides having the "primitive" types (scalars) that in the old versions of PHP could not be used as hinting type parameters. In version 7 this turned into type declaration and can be used in any function.
As it is PHP has a lot of care to use this effectively, so a read in the documentation is critical.
In case a class?
A type can be defined by a class.
5
This resource is called Type Hinting.
It serves to determine that a parameter needs to have a certain type. Before PHP 7, no scalar types were supported( int, float, bool and string ). In the example you showed, the parameter $logger
must have the type LoggerInterface
. If he doesn’t, an exception is made.
The Type Hinting is widely used, mainly by Frameworks, because it allows to ensure that if the "contracts" defined by signing a method are not fulfilled, an exception will be cast. This was more complete with the release of PHP 7, with scalar type support.
To read more about Type Hinting: http://php.net/manual/en/language.oop5.typehinting.php
Browser other questions tagged php oop function typing
You are not signed in. Login or sign up in order to post.
Assign type to parameters and What the application gains using Type Hint?
– rray