Today, when making a product, I accidentally saw a line of code,
$c = New$class_name; $object _os= Newstdclass; $c->on_init_app_router ($object _os);
Very puzzled, so went to class $c to see a bit, found that the original is the empty class Stdclass instance $object_os Some properties of the dynamic Add.
From the above three lines of code, we can roughly see what stdclass can do for us.
Stdclass in the product code to see a few times, but they did not use, so looked up a bit of relevant information, the summary of the experience summarized as follows.
Stdclass is a base class for PHP, and almost all classes inherit this class, so any time it can be new, you can make this variable an object. At the same time, there is a special place in this base class, there is no method.
Stdclass is becoming popular in PHP5, because the uniqueness of PHP5 objects, where objects are invoked anywhere, are referred to as address types, so the relative consumption of resources will be less. When the other page assigns a value to it, it is modified directly instead of referencing a copy.
For example:
$user = Newstdclass (); $user->name = ' Gouki '; $myUser = $user; $myUser->name = ' Flypig ';
If in the PHP4 era, such code is the consumption of system resources. Because:
$myUser = $user;
This is the creation of a copy. So, when it comes to PHP4, it's used like this:
$myUser = & $user;
From the beginning of the article three lines of code we can see, stdclass can be used to generate the object type of the element, then, we will pass an array to the object class through Stdclass to lead to the conversion of several array objects to each other method:
One, Stdclass array to Object
$arr = Array (); $arr [' a '] = 1; $arr [' b '] = 2; $arr [' c '] = 3; $object = Newstdclass;foreach ($arras $key=> $value) { $object $key = $value;} Var_dump ($object);
The resulting output is as follows:
Object (StdClass) #1 (3) { ["a"]=> int (1) ["B"]=> int (2) ["C"]=> int (3)}
Second, the object to the array
Functionobject_to_array ($obj) { $_arr= is_object ($obj)? Get_object_vars ($obj): $obj; foreach ($_arras$key=> $val) { $val = (Is_array ($val) | | is_object ($val))? Object_to_array ($val): $val; $arr [$key] = $val; } Return$arr; }
Three, Arrayobject method array to Object
$arr = Array (' key1 ' = ' test1 ', ' key2 ' = ' test2 '); Var_dump (Newarrayobject ($arr));
The resulting output is as follows:
Object (Arrayobject) #1 (1) { ["Storage": "Arrayobject":p rivate]=> Array (2) { ["Key1"]=> String (5) "Test1" ["Key2"]=> string (5) "Test2"} }
Of course, PHP is powerful and flexible, and there must be many other ways to convert arrays to objects.