Typehinting: the method must accept any $ arg being an object

I have a class 'Collection' that has an add method. The add method should only accept objects. So this is the desired behavior:

$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

According to the PHP manual, you can introduce typehint methods, previously using the $argclass name. Since all PHP classes are children stdClass, I realized that this method signature would work:

public function add(stdClass $obj);

But it fails: "The argument must be an instance of stdClass."

If I change the signature to the 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 enter a hint for a shared object?

+3
source share
3

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 .

+5

PHP . stdClass:

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

-, PHP object, object - PHP (, array), typecasting to object stdClass:

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

, , , is_object($obj) false.

+4

Well, the thing is that PHP is still a dynamic language, and type hints are just that: hints. I think you will have to go back to the old is_object or similar methods and throw a custom exception.

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

Source: https://habr.com/ru/post/1775711/


All Articles