Home >Backend Development >PHP Tutorial >Understanding the stdClass class in PHP_PHP Tutorial

Understanding the stdClass class in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:32:151137browse

I believe that everyone, like me, will often see PHP code similar to the following:

Copy code The code is as follows:

$user = new stdClass();
$user->name = 'gouki';

What is this code used for?
Open the manual and search for stdClass. You will find that there is almost no introduction in the manual. If you search Google again, you will see almost all English explanations.
In fact, stdClass only became popular in PHP5. And stdClass is also a reserved class of zend. It seems to have no other effect. There is also almost no explanation.
Or, we can understand it this way: stdClass is a base class of PHP. Almost all classes inherit this class, so it can be new at any time and this variable can become an object. At the same time, this base class has a special feature, that is, it has no methods.
Whenever a variable of new stdClass() is used, it is impossible to use $a->test().
Or, we can understand it this way. Because of the uniqueness of PHP5 objects, objects are referenced wherever they are called, so they will consume less resources. When assigning a value to it on other pages, it is modified directly instead of referencing a copy.
For example:

Copy code The code is as follows:

$user = new stdClass();
$user ->name = 'gouki';
$myUser = $user;
$myUser->name = 'flypig';

If in the PHP4 era, such code is consuming the system resource. Because:
$myUser = $user;
This creates a copy. Therefore, in PHP4, it is used like this:
Copy code The code is as follows:

$myUser = & $user ;

Some people say, why not use arrays? Wouldn't arrays be more convenient? And for weakly typed programs like PHP, using arrays should be the most convenient.
Indeed. Arrays should be the most convenient to use in programs. However, every time the array is referenced ($a = $b), a copy is actually created. Moreover, after the array is unset, it still occupies memory (this is what I heard) People say it, I haven’t tested it... and I don’t know how to test it. If anyone knows, please tell me, thank you)
However, there is also a function arrayobject in the standard class library of SPL, which can directly convert an array into an object. This is also a good idea.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/756341.htmlTechArticleI believe that everyone, like me, will often see PHP code similar to the following: Copy the code as follows: $ user = new stdClass(); $user-name = 'gouki'; What is this code used for...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn