stdClass allows you to create (essentially) faceless objects. For instance:
$object = (object) array( 'name' => 'Trevor', 'age' => 42 );
As shown here, the fastest way to create an stdClass object is to create an associative array. For multiple levels, you again do the same inside:
$object = (object) array( 'name' => 'Trevor', 'age' => '42', 'car' => (object) array( 'make' => 'Mini Cooper', 'model' => 'S', 'year' => 2010 ) );
Another method is to convert an associative array to an object followed by a recursive function. Here is an example.
function toObject(array $array) { $array = (object) $array; foreach ($array as &$value) if (is_array($value)) $value = toObject($value); return $array; }
This is useful if you are not an associative array.
Unfortunately, although PHP 5.3 supports anonymous methods, you cannot put an anonymous method in stdClass (although you can put it in an associative array). But this is not so bad; if you need functionality, you really need to create a class.
source share