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
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);
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?
Unlike Java’s
Objectclass, PHP does not have a base class for objects. Objects do not inheritstdClass: 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:Luckily, PHP already defines the
InvalidArgumentExceptionclass for that purpose.