When the PHP kernel performs module initialization operation, this function will be loaded automatically . In this way, the registration operation of the stdClass class will also be executed. The stdClass class is a class with no member variables and no member methods. All its magic methods, parent classes, interfaces, etc. are set to NULL during initialization. Since we cannot dynamically add methods to a class in PHP, this class can only be used to handle dynamic attributes, which is also a common usage. Therefore, the following method will not trigger the set interceptor
stdclass can be used as a base class. Its biggest feature is that (its derived classes) can automatically add member variables without the need to explain them when defining.
All php variables are instances of stdClass.
How to use:
1. Use stdclass:
$andy = array(); $andy = (object)$andy; $andy->a = 1; $andy->b = 2; $andy->c = 3;
In this way, the quantities a, b, and c are filled in stdclass. This saves trouble, because to create an empty object requires $andy = new Andy; and there must be a class Andy{} first. Another example:
<?php $a = new stdClass(); $a->id = '11 '; $a->username = 'me'; print_r($a); ?>
will output: stdClass Object ( [id] => 11 [username] => me ).
Many times this method is used to replace the use of array, which is just a change of syntax.
2. Reading:
stdClass Object ( [getWeatherbyCityNameResult] => stdClass Object ( [string] => Array ( [0] => 四川 [1] => 成都 [2] => 56294 [3] => 56294.jpg [4] => 2009-5-17 13:52:08 [5] => 26℃/19℃ [6] => 5月17日 阴转阵雨 ) ) )
In fact, it is similar to array, but the access method changes a little. We are generally accustomed to using array['key'] to access arrays.
For this kind of stdClass, as in the above example, $weather->getWeatherbyCityNameResult->string[0] can access properties like this, and the result will be "Sichuan".
3. Instantiation, new.
Compare these two codes:
<?php $a = array(1=>2,2=>3); $a = (object)$a; $a->id = '11 '; $a->username = 'me'; print_r($a); ?>
Will output: stdClass Object ( [1] => 2 [2] => 3 [id] => 11 [username] = > me ).
<?php $a = array(1=>2,2=>3); $a = (object)$a; $a = new stdClass(); $a->id = '11 '; $a->username = 'me'; print_r($a); ?>
Will output: stdClass Object ( [id] => 11 [username] => me ).
It turns out that after instantiating with new, the previous array is cleared, leaving only the ones added later. If not instantiated, stdClass will retain all elements.
It should be noted that when using global and static in a function and new stdclass is referenced, &new stdclass will be invalid. Avoid using references and use them directly. new stdclass.
The above is the detailed content of Detailed explanation of the usage of stdClass in php. For more information, please follow other related articles on the PHP Chinese website!