Since PHP objects don't inherit from any base class (including stdClass
), there is no support for type hinting a generic object type.
For example, the below will not work.
<?php
function doSomething(object $obj) {
return $obj;
}
class ClassOne {}
class ClassTwo {}
$classOne= new ClassOne();
$classTwo= new ClassTwo();
doSomething($classOne);
doSomething($classTwo);
And will throw a fatal error:
Fatal error: Uncaught TypeError: Argument 1 passed to doSomething() must be an instance of object, instance of OperationOne given
A workaround to this is to declare a degenerate interface that defines no methods, and have all of your objects implement this interface.
<?php
interface Object {}
function doSomething(Object $obj) {
return $obj;
}
class ClassOne implements Object {}
class ClassTwo implements Object {}
$classOne = new ClassOne();
$classTwo = new ClassTwo();
doSomething($classOne);
doSomething($classTwo);