This article mainly introduces the Stdclass usage in PHP, and analyzes the function, principle, use method and related precautions of stdclass in PHP in combination with instance form, and the friends who need can refer to the following
The examples in this article describe Stdclass usage in PHP. Share to everyone for your reference, as follows:
PHP Stdclass in our development of the use of the application is not much, but PHP stdclass role is very large, let's look at the use of PHP stdclass.
Many places in WordPress use Stdclass to define an object (usually in the form of an array), and then use Get_object_vars to "convert" the defined object into a group.
As shown in the following code:
$tanteng = new StdClass (); $tanteng->name = ' Tanteng '; $tanteng->email = ' xxx@qq.com '; $info = Get_object_vars ($ Tanteng);p Rint_r ($info); exit;
Output:
Array ([name] = + Tanteng [email] = xxx@qq.com)
The function of Get_object_vars is to return an associative array that consists of object properties. The effect is exactly the same as defining an array:
$tanteng = Array (), $tanteng [' name '] = ' tanteng '; $tanteng [' email '] = ' xxx@qq.com ';
It can be understood that Stdclass is a built-in class that does not have a member variable or a class of member methods, and a new stdclass is an instantiation of an "empty" object, which itself makes little sense, but what are the benefits of using the Stdclass definition?
The following code:
$user = new StdClass (); $user->name = ' Gouki '; $user->hehe = ' hehe '; $myUser = $user; $myUser->name = ' Flypig ';p rint _r ($user);p rint_r ($myUser);p rint_r ($user);
Here $myuser is assigned value $user, but actually did not open a new memory storage variables, $myUser or Stdclass This object, through the $myuser change the property page changed the $user properties, not a new copy, if there are many such operations in the program , you can save memory overhead by using the Stdclass method.
Operation Result:
StdClass object ( [name] = Flypig [hehe] = hehe) StdClass object ( [name] = = Flypig [hehe] = > hehe) stdClass Object ( [name] = Flypig [hehe] = hehe)
As can be seen from the results, changing the properties of the $myuser does change the Stdclass property of the $user declaration, and if $user is an array that assigns to $myuser, it copies a copy to $myuser, which increases the overhead of the system.
Of course, you can also convert an array to an object in turn:
$hehe [' he1 '] = ' he1 '; $hehe [' he2 '] = ' he2 '; $hh = (object) $hehe;p rint_r ($HH);
Printing results:
StdClass Object ([he1] = he1 [He2] = he2)