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

Understanding the stdClass class in PHP

高洛峰
高洛峰Original
2016-12-21 14:22:23945browse

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

$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 the variables of new stdClass() are used, it is impossible to use $a->test().
Or, we can understand it this way, precisely because of the uniqueness of PHP5 objects, objects are of the reference address type when called anywhere, so relatively less resources will be consumed. When assigning values ​​to it on other pages, it is modified directly instead of referencing a copy.
For example:

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

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

$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, in the standard class library of SPL, there is also a function arrayobject, which can directly convert an array into an object. This is also What a good idea.

For more articles related to understanding the stdClass class in PHP, please pay attention to the PHP Chinese website!


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