Wednesday, 5 October 2016

What is stdClass in PHP?



Please define what stdClass is.


Answer



stdClass is PHP's generic empty class, kind of like Object in Java or object in Python (Edit: but not actually used as universal base class; thanks @Ciaran for pointing this out).



It is useful for anonymous objects, dynamic properties, etc.




An easy way to consider the StdClass is as an alternative to associative array. See this example below that shows how json_decode() allows to get an StdClass instance or an associative array.
Also but not shown in this example, SoapClient::__soapCall returns an StdClass instance.



//Example with StdClass
$json = '{ "foo": "bar", "number": 42 }';
$stdInstance = json_decode($json);
echo $stdInstance->foo . PHP_EOL; //"bar"
echo $stdInstance->number . PHP_EOL; //42
//Example with associative array

$array = json_decode($json, true);
echo $array['foo'] . PHP_EOL; //"bar"
echo $array['number'] . PHP_EOL; //42


See Dynamic Properties in PHP and StdClass for more examples.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...