What would a parameter call before the string in a function

2

I've seen several times do this:

interface LoggerAwareInterface
{
     public function setLogger(LoggerInterface $logger);
}  

Put a parameter before the variable, in case what would it be and what does it do?

    
asked by anonymous 06.03.2016 / 20:05

2 answers

7

This is not a parameter, the parameter is $logger . What comes before, LoggerInterface the type of the parameter. That is, PHP will only accept a call to this method if an argument of this data type is passed . So the method happens to have a signature that is fundamental in interfaces.

It seems a bit strange in PHP because it is a dynamic typing language, but it is common in other languages and for some tasks in PHP this is useful for making the code more robust. For its dynamic feature, robustness will only occur with tests, since instead of compiling, the error will only be discovered at runtime by throwing an exception.

A type can be defined by classes, or interfaces, as in the example, or traits as well as having the "primitive" types (scalar) that in old versions of PHP could not be used as < in> type hinting parameters. In version 7 this has become type declaration and can be used in any function.

How PHP is has a lot of care to use this effectively. So one handles the documentation is fundamental.

    
06.03.2016 / 20:19
5

This feature is called Type Hinting .

It serves to determine that a parameter must have a particular type. Before PHP 7, scalar types ( int , float , bool and string ) were not supported. In the example you showed, the parameter $logger must have type LoggerInterface . If it does not, an exception is thrown.

Type Hinting is used a lot, mainly by Frameworks , because it allows to ensure that, if the "contracts" defined by the signature of a method are not fulfilled, exception will be thrown. This was more complete with the release of PHP 7, with support for scalar types.

To read more about Type Hinting : link p>     

06.03.2016 / 23:55