代码之家  ›  专栏  ›  技术社区  ›  dnagirl

typehinting:方法应接受任何属于对象的$arg

  •  3
  • dnagirl  · 技术社区  · 14 年前

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

    有人知道如何键入一般对象的提示吗?

    4 回复  |  直到 7 年前
        1
  •  5
  •   netcoder    14 年前

    不像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");
        }
    }
    

    幸运的是,php已经定义了 InvalidArgumentException 为了这个目的。

        2
  •  4
  •   BoltClock    14 年前

    PHP中没有根类。对象甚至不从继承 stdClass :

    class Foo {}
    var_dump(new Foo instanceof stdClass); // bool(false)
    var_dump(get_parent_class(new Foo));   // bool(false)
    

    显然,在php中没有已知的方法来为 object 尽管 对象 是php中的数据类型(如 array )和类型转换为 对象 产量A STD类 对象:

    echo get_class((object) "string"); // stdClass
    

    我想作为一个解决方法,如果 is_object($obj) 返回false。

        3
  •  0
  •   Daff    14 年前

    事实上,PHP仍然是一种动态语言,类型提示就是:提示。我想你得回到过去 is_object 或类似的方法并引发自定义异常。

    class Collection {
      public function add(Base $obj){
        if(!is_object($obj))
        throw new Exception("Parameter must be an object");
        // do stuff
      }
    }
    
        4
  •  0
  •   Adam    7 年前

    在php 7.2中,现在有一个 object 类型提示。你可以简单地做

    class Collection {
      public function add(object $obj){
        //do stuff
      }
    }