我读了一些脚本和 我无法理解为什么他们将类名放在其他类的构造函数中:
public function __construct(AclassName $foo){
$this->foo=$foo;
}
答案 0 :(得分:8)
因为他们希望$foo
只是AclassName
的实例。不是数组,数字,字符串或类的实例,不是AclassName
也不是AclassName
。在PHP中称为type hinting,虽然它们不是真正的提示,而是强制执行。
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
也可以在接口或抽象类上完成提示:
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
答案 1 :(得分:2)
这将在与AclassName
实例相关联的类的实例中创建引用。据推测,与构造函数关联的类的实例将与AclassName
实例协作以履行其一项或多项职责。
答案 2 :(得分:1)
这称为类型提示,并在PHP5中添加。基本上,这意味着方法/函数的参数的提供值必须是该类名的实例。如果不是,那么PHP引擎将抛出可捕获的致命错误。
以下是基于您提供的代码段的简单示例:
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);
类型提示,就像instanceof
运算符一样考虑类继承和接口实现。
答案 3 :(得分:0)
AclassName
是一个类型提示。这意味着,传递给构造函数的第一个参数必须是AclassName
的实例。