我有一个类 '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
根据 PHP 手册,可以通过在 前面$arg
加上类名来输入提示方法。由于所有 PHP 类都是 的子类stdClass
,我认为这个方法签名会起作用:
public function add(stdClass $obj);
但它因“参数必须是 stdClass 的实例”而失败。
如果我将签名更改为我定义的父类,那么它可以工作:
class Collection {
public function add(Base $obj){
//do stuff
}
}
$collection->add($foo); //$foo is class Foo which is an extension of Base
有谁知道如何为通用对象键入提示?