typehinting:方法应接受任何作为对象的$ arg [英] typehinting: method should accept any $arg that is an object
问题描述
我有一个'Collection'类,它具有一个add方法. add方法应仅接受对象.因此,这是所需的行为:
I have a class 'Collection', which has an add method. The add method should only accept objects. So this is the desired behaviour:
$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
的子类,因此我认为此方法签名可以工作:
According to the PHP manual, one can typehint methods by prefacing the $arg
with a class name. Since all PHP classes are children of stdClass
, I figured this method signature would work:
public function add(stdClass $obj);
但是它失败并显示参数必须是stdClass的实例".
But it fails with "Argument must be an instance of stdClass".
如果我将签名更改为我定义的父类,那么它将起作用:
If I change the signature to a parent class defined by me, then it works:
class Collection {
public function add(Base $obj){
//do stuff
}
}
$collection->add($foo); //$foo is class Foo which is an extension of Base
有人知道如何为通用对象键入提示吗?
Does anyone know how to type hint for a generic object?
推荐答案
与Java的Object
类不同,PHP 没有对象的基类.对象不继承stdClass
:这是默认的对象实现,而不是基类.因此,不幸的是,您不能为PHP中的所有对象键入提示.您必须执行以下操作:
Unlike Java's Object
class, PHP does not have a base class for objects. Objects do not inherit stdClass
: it's a default object implementation, not a base class. So, unfortunately, you can't type hint for all objects in PHP. You have to do something like:
class MyClass {
public function myFunc($object) {
if (!is_object($object))
throw new InvalidArgumentException(__CLASS__.'::'.__METHOD__.' expects parameter 1 to be object");
}
}
幸运的是,PHP已经为此目的定义了InvalidArgumentException
类.
Luckily, PHP already defines the InvalidArgumentException
class for that purpose.
这篇关于typehinting:方法应接受任何作为对象的$ arg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!