This article analyzes the usage of stdclass in PHP. Share to everyone for your reference. The specific analysis is as follows:
Stdclass is one of several predefined classes in PHP and is a zent reserved class. It's actually a base class provided by PHP, is a blank class with nothing in it, we can instantiate it, then define a series of variables that pass through the variable (many PHP programmers use it to pass the values of a series of variables while they don't bother to create a class of their own). However, you can only pass properties because you cannot add a method after instantiating it. Because once a class is materialized, you cannot add a method.
Stdclass can be used as a base class, with the greatest feature being that (its derived classes) can automatically add member variables without being described in the definition.
All PHP variables are instances of Stdclass.
How to use:
1, the use of Stdclass:
$andy = Array ();
$andy = (object) $andy;
$andy->a = 1;
$andy->b = 2;
$andy->c = 3;
So the quantity A, B, C is filled in the stdclass. This is easy, because the new empty to the image but to $andy = new Andy; And you have to have a class andy{} first. Another example:
<?php
$a = new StdClass ();
$a->id = ' one ';
$a->username = ' me ';
Print_r ($a);
? >
will be output: StdClass Object ([id] => [username] => me).
Many times the use of this method instead of the array is just a different form of syntax.
2. READ:
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 turn showers))
In fact, the same as array, but the way of access to change a little bit, we are generally accustomed to using array[' key ' this way to access the array.
For this stdclass, as in the previous example, $weather->getweatherbycitynameresult->string[0] can access the property in this way, which will result in "Sichuan".
3, instantiation, new.
Compare the two codes:
<?php
$a = array (1=>2,2=>3);
$a = (object) $a;
$a->id = ' one ';
$a->username = ' me ';
Print_r ($a);
? >
Output: StdClass Object ([1] => 2 [2] => 3 [id] => one [username] => me.
<?php
$a = array (1=>2,2=>3);
$a = (object) $a;
$a = new StdClass ();
$a->id = ' one ';
$a->username = ' me ';
Print_r ($a);
? >
Output: StdClass Object ([id] => [username] => me).
Once instantiated with new, the preceding array is emptied, leaving behind the added, and if not instantiated, Stdclass will retain all elements.
It should be noted that in the function of the use of global, static when the new Stdclass reference, then &new Stdclass will be invalidated, should avoid using references, directly with the new Stdclass.
I hope this article will help you with your PHP program design.