Saturday 6 April 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...