相关疑难解决方法(0)

1014
推荐指数
15
解决办法
55万
查看次数

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

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

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

php oop type-hinting php-5.3

3
推荐指数
1
解决办法
239
查看次数

标签 统计

php ×2

oop ×1

php-5.3 ×1

stdclass ×1

type-hinting ×1