我有一個類'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
typehint方法。由於所有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
有誰知道如何爲一個通用的對象類型暗示?
'assert(is_object($ arg));'是你所需要的。 – mario 2010-11-18 21:58:47