I read some scripts and I cannot understand why they put a class name in a constructor of other class:
public function __construct(AclassName $foo){
$this->foo=$foo;
}
I read some scripts and I cannot understand why they put a class name in a constructor of other class:
public function __construct(AclassName $foo){
$this->foo=$foo;
}
This creates a reference in an instance of the class associated with the constructor to an instance of AclassName. Presumably, then, the instance of the class associated with the constructor will collaborate with the AclassName instance to fulfill one or more of its responsibilities.
Because they want $foo to be an instance of AclassName only. Not an array, number, string, or an instance of a class that is not AclassName nor extends AclassName. In PHP is called type hinting, although they're not really hints, but enforcements.
function foo (array $bar) {
// $bar must be an array, otherwise an E_RECOVERABLE_ERROR is thrown
}
function baz (ClassName $bar) {
// $bar must be an instance of ClassName
}
baz(new ClassName); // works OK
baz(new StdClass); // error
class ExtendsFromClassName extends ClassName
{}
baz(new ExtendsFromClassName); // works OK
Hinting may be done on interfaces or abstract classes too:
interface SomeInterface
{}
function baz(SomeInterface $object) {
// $object must be an instance of a class which implements SomeInterface
}
class Foo implements SomeInterface
{}
baz(new Foo); // works OK
This is called Type Hinting, and was added in PHP5. Basically, it means that the supplied value for that argument of the method/function must be an instance of that class name. If it is not, the PHP engine will throw a catchable fatal error.
Here's a simple example based on the snippet you provided:
class AnotherClass
{
/**
* @var SomeClass
*/
protected $_someClass;
public function __construct(SomeClass $some) {
$this->_someClass = $some;
}
}
$someClass = new SomeClass();
$differentClass = new DifferentClass();
// Fatal Error: Argument 1 must be an instance of SomeClass
$anotherClass = new AnotherClass($differentClass);
$anotherClass = new AnotherClass('a string');
// That's ok!
$anotherClass = new AnotherClass($someClass);
Type hinting, like the instanceof operator takes class inheritance and interface implementation into consideration.
You can find the relevant PHP manual page here.
AclassName is a type-hint. This means, that the first argument passed to the constructor must be an instance of AclassName.