我读了一些脚本,我无法理解为什么他们将类名放在其他类的构造函数中:
public function __construct(AclassName $foo){
$this->foo=$foo;
}
Run Code Online (Sandbox Code Playgroud)
因为他们只想$foo成为一个实例AclassName.不是数组,数字,字符串或类的实例,不是AclassName也不是扩展AclassName.在PHP中称为类型提示,虽然它们不是真正的提示,而是强制执行.
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
Run Code Online (Sandbox Code Playgroud)
提示也可以在接口或抽象类上完成:
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
Run Code Online (Sandbox Code Playgroud)