我有一个类'Collection',它有一个add方法.add方法应该只接受对象.所以这是理想的行为:
$x=5;//arbitrary non-object
$obj=new Foo; //arbitrary object
$collection=new Collection;
$collection->add($obj); //should be acceptable arg, no matter the actual class
$collection->add($x); //should throw an error because $x is not an object
Run Code Online (Sandbox Code Playgroud)
根据PHP手册,可以通过$arg使用类名称前缀来输入提示方法.由于所有PHP类都是子类stdClass,我认为这个方法签名可以工作:
public function add(stdClass $obj);
Run Code Online (Sandbox Code Playgroud)
但它失败了"Argument必须是stdClass的一个实例".
如果我将签名更改为我定义的父类,那么它的工作原理如下:
class Collection {
public function add(Base $obj){
//do stuff
}
}
$collection->add($foo); //$foo is class Foo which is an extension of Base
Run Code Online (Sandbox Code Playgroud)
有谁知道如何为通用对象键入提示?