Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stdClass and type hinting

Tags:

php

$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

like image 321
Kirzilla Avatar asked Nov 08 '12 10:11

Kirzilla


People also ask

What is an stdClass?

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.

What does stdClass mean 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.


2 Answers

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;
}
like image 89
zerkms Avatar answered Oct 17 '22 15:10

zerkms


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)
like image 24
Jocelyn Avatar answered Oct 17 '22 17:10

Jocelyn