Home>Article>Backend Development> Analysis of how PHP uses new StdClass() to create an empty object

Analysis of how PHP uses new StdClass() to create an empty object

不言
不言 Original
2018-04-28 15:06:38 1871browse

This article mainly introduces the method of PHP using new StdClass() to create empty objects. It analyzes the creation and use of PHP empty objects based on specific examples. Friends in need can refer to the examples in this article.

Describes how PHP uses new StdClass() to create an empty object. Share it with everyone for your reference, the details are as follows:

PHP can use$object = new StdClass();to create an empty object without member methods and properties.

Many times, programmers will put some information such as parameter configuration items in arrays for use, but array operations are not very convenient. Many times, object operators->xxx are used instead of array operations. The symbol ['xxx'] is much more convenient. So you need to create an empty object to store the required attribute names and attribute values into the object.

However, there is no syntax likevar object = {};in Javascript in PHP.

PHP can use at least 3 methods to create an empty object

Method 1: Write an empty class

It can barely complete the task, but there is nothing special pattern.

dbhost = 'www.jb51.net'; echo $cfg->dbhost; ?>

Method 2: Instantiate the StdClass class

The StdClass class is a base class in PHP. However, what is strange is that it is almost never mentioned in the PHP manual. This class, at least in the PHP index, cannot be searched.

The StdClass class does not have any member methods or member attributes. After instantiation, it is an empty object.

dbhost = 'www.jb51.net'; echo $cfg->dbhost; ?>

Method 3: Tossing json_encode() and json_decode()

This method is to pass an empty JSON object throughjson_decode()Convert to PHP's StdClass empty object.

Similarly, you can convert an array into JSON throughjson_encode(), and then convert JSON into a StdClass object throughjson_decode(),

For these two functions, please refer to the PHP manual.

dbhost = 'www.jb51.net'; echo $cfg->dbhost; ?>

Related recommendations:

PHP uses Curl to implement simulated login and data capture function examples


The above is the detailed content of Analysis of how PHP uses new StdClass() to create an empty object. For more information, please follow other related articles on 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