This article mainly introduces the usage of stdClass in php, and analyzes the functions and usage techniques of stdClass with examples. It has certain reference value and is needed Friends can refer to it
This article analyzes the usage of stdClass in php with examples. Share it with everyone for your reference. The specific analysis is as follows:
stdclass is one of several predefined classes in php and is a class reserved by zent. In fact, it is a base class provided by PHP, which is a blank class with nothing in it. We can instantiate it, then define a series of variables, and pass variables through it (many PHP programmers use it to Pass the values of a series of variables while not bothering to create a class of your own). However, since methods cannot be added after instantiation, only properties can be passed. Because once a class is instantiated, methods cannot be added.
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 specify them when defining.
All php variables are instances of stdClass.
How to use:
1. Use stdclass:
?
3 4
5
|
$andy->a = 1; $andy->c = 3;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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日 阴转阵雨 ) ) ) |
1 2 3 4 5 6 | <🎜>$a = new stdClass();<🎜> <🎜>$a->id = '11 '; $a->username = 'me'; print_r($a); ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | stdClass Object ( [getWeatherbyCityNameResult] => stdClass Object ( [string] => Array ( [0] => Sichuan [1] => Chengdu [2] => 56294 [3] => 56294.jpg [4] => 2009-5-17 13:52:08 [5] => 26℃/19℃ [6] => May 17, cloudy to showers ) ) ) |
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 the attribute like this, and the result will be "Sichuan".
3. Instantiation, new.
Compare these two codes:
?
3 4
5
6
|
$a = array(1=>2,2=>3); $a = (object)$a; $a->id = '11 '; $a->username = 'me'; print_r($a);
|
1
2 |
<🎜>$a = array(1=>2,2=>3); $a = (object)$a; $a = new stdClass(); $a->id = '11 '; $a->username = 'me'; print_r($a); ?> |