$obj = new stdClass();
echo gettype($obj); //object
function abc(object $obj) {
return;
}
abc($obj); //Catchable fatal error: Argument 1 passed to abc() must be an instance of object, instance of stdClass given
Why calling abc($obj)
triggers error?
Catchable fatal error: Argument 1 passed to abc() must be an instance of object, instance of stdClass given
The stdClass is a generic empty class used to cast the other type values to the object. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. The stdClass is not the base class for objects in PHP.
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
Because type hinting works only for class name, interface name or array
. There is no common ancestor object
(like in some other programming languages like C#) in php object model. What you have to specify is stdClass
As of php 7.2 it's now possible to use object
type hint exactly as you guessed in your question:
function abc(object $obj) {
return;
}
Read the documentation about type hinting in PHP.
Your current code forces abc
function to accept a parameter that is an instance of the class object
(a class named object
!).
Do that instead:
function abc(stdClass $obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With