stdClass in php

stdClass is php's generic empty class or say default PHP object which has no predefined members, kind of like Object in Java
you cannot define a class named stdClass in your PHP code. Useful for anonymous objects, dynamic properties,

StdClass object creation. Something like this would be great:

$foo = {”bar”: “baz”, “bam”: “boom”};

so you end up doing something like this:

$foo = new StdClass;
$foo->bar = “baz”;
$foo->bam = “boom”;

but you don’t have to. Using PHP’s casting operator you can create the object in one line:
$foo = (object) array(”bar” => “baz”, “bam” => “boom”);

usage is casting an array to an object which takes each value in the array and adds it as a member variable with the name based on the key
in the array.

Here’s an example below that converts an array to an object below. This method is called Type Casting

'Divyesh',
'lastname' => 'Karelia'
);

$p = (object) $person;
echo $p->firstname; // Will print 'Divyesh'
?>


Here’s an example below that converts a multi-dimensional array to an object. This is accomplished through recursion.

02.function arrayToObject($array) {
03. if(!is_array($array)) {
04. return $array;
05. }
06.
07. $object = new stdClass();
08. if (is_array($array) && count($array) > 0) {
09. foreach ($array as $name=>$value) {
10. $name = strtolower(trim($name));
11. if (!empty($name)) {
12. $object->$name = arrayToObject($value);
13. }
14. }
15. return $object;
16. }
17. else {
18. return FALSE;
19. }
20.}
21.?>


array('name' => 'Divyesh'),
'last' => array('name' => 'Karelia')
'
);

$p = arrayToObject($person);
?>

first->name; // Will print 'Divyesh'
?>

No comments: