Aug 16, 2011

PHP: Playing with StdClass

What is StdClass and where does it live?

StdClass is a document class in PHP with no predefined members. Its the class that is created when you cast something to object like this:

$obj = (object) $something;

Sounds good but how to get its members if we don’t know about them? Actually, its very easy and we have several approaches.

First, we can iterate through its members with foreach:
foreach ($obj as $key => $value) {
   
}
Second we can cast our object to array:

$array = (array) $obj;

Or get its members as array:

get_object_vars($obj);

What else we can do with StdClass?
We can create objects and assign members:
$std = new StdClass();
$std->key = "value";
and access them:
echo $std->key;
If you see an error like this:
Catchable fatal error: Object of class stdClass could not be converted to string
the culprit is our stdClass of course. Maybe you are trying to print an object of this class.

Read how to use SOAP with PHP

No comments:

Popular Posts