typehinting:方法应该接受任何$ arg作为对象

dna*_*irl 3 php oop type-hinting php-5.3

我有一个类'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)

有谁知道如何为通用对象键入提示?

net*_*der 5

与Java的Object类不同,PHP 没有对象的基类.对象不继承stdClass:它是默认对象实现,而不是基类.所以,遗憾的是,您无法为PHP中的所有对象键入提示.你必须这样做:

class MyClass {
    public function myFunc($object) {
        if (!is_object($object))
             throw new InvalidArgumentException(__CLASS__.'::'.__METHOD__.' expects parameter 1 to be object");
    }
}
Run Code Online (Sandbox Code Playgroud)

幸运的是,PHP已经InvalidArgumentException为此目的定义了类.