STDCLASS usage instance analysis in PHP and stdclass instance analysis
This example describes the usage of STDCLASS in PHP. We will share this with you for your reference. The details are as follows:
In PHP, STDCLASS is not used much in our development and application, but STDCLASS is very useful in PHP. Let's take a look at the usage of STDCLASS in PHP.
In WordPress, stdClass is used in many places to define an object (instead of an array), and get_object_vars is used to convert the defined object into an array.
The following code is used:
$tanteng = new stdClass();$tanteng->name = 'tanteng';$tanteng->email = 'xxx@qq.com';$info = get_object_vars($tanteng);print_r($info);exit;
Output:
Array ( [name] => tanteng [email] => xxx@qq.com )
Get_object_vars is used to return an associated array composed of object attributes. Its effect is the same as defining arrays like this:
$tanteng = array();$tanteng['name'] = 'tanteng';$tanteng['email'] = 'xxx@qq.com';
It can be understood as follows: stdClass is a built-in class with no member variables or member methods. A new stdClass instantiates an "null" object, it is meaningless, but what are the advantages of stdClass definition?
The following code:
$user = new stdClass();$user->name = 'gouki';$user->hehe = 'hehe';$myUser = $user;$myUser->name = 'flypig';print_r($user);print_r($myUser);print_r($user);
$ MyUser is assigned $ user, but there is no new memory storage variable. $ myUser still refers to the stdClass object, the $ myUser attribute page is changed by changing the $ user attribute, instead of creating a new copy. If there are many such operations in the program, using stdClass can save memory overhead.
Running result:
stdClass Object( [name] => flypig [hehe] => hehe)stdClass Object( [name] => flypig [hehe] => hehe)stdClass Object( [name] => flypig [hehe] => hehe)
The result shows that changing the $ myUser attribute does change the stdClass attribute declared by $ user. If $ user is an array, it is assigned to $ myUser, copy a copy to $ myUser to increase the system overhead.
Of course, you can also convert an array into an object:
$hehe['he1'] = 'he1';$hehe['he2'] = 'he2';$hh = (object) $hehe;print_r($hh);
Print result:
stdClass Object ( [he1] => he1 [he2] => he2 )