The object
Type
The object
type can be used in the signature of a
function or method to express that an object is expected:
function f(object $o)
{
// ...
}
f('not an object');
Executing the code shown above will print the output shown below:
Fatal error: Uncaught TypeError:
Argument 1 passed to f() must be an object, string given in ...
Following the concept of contravariance, a child class may
broaden the type of a parameter from a specific class or interface
to the generic object
type:
class ParentClass
{
public function m(Foo $o)
{
}
}
class ChildClass extends ParentClass
{
public function m(object $o)
{
}
}
However, a child class should not narrow the type of a parameter
from the generic object
type to a specific class or
interface:
class ParentClass
{
public function m(object $o)
{
}
}
class ChildClass extends ParentClass
{
public function m(Foo $o)
{
}
}
Executing the code shown above will print the output shown below:
Warning: Declaration of ChildClass::m(Foo $o) should be
compatible with ParentClass::m(object $o) in ...
Following the concept of covariance, a child class may narrow the
return type of a method from the generic object
type to
a specific class or interface:
class ParentClass
{
public function m(): object
{
return new stdClass;
}
}
class ChildClass extends ParentClass
{
public function m(): Foo
{
return new Foo;
}
}