The example 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 $<a href="http://www.php.cn/wiki/60.html" target="_blank">object</a> = new StdClass();
to create a method without members Empty objects for 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, objects are used operators- >xxx is much more convenient than the array operator ['xxx']. 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 like var object = {}; in PHP Javascript
.
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.
<?php class cfg { } $cfg = new cfg; $cfg->dbhost = 'www.jb51.net'; echo $cfg->dbhost; ?>
Method 2: Instantiate the StdClass class
The StdClass class is a base class in PHP, but the weird thing is in the PHP Manual Xue almost never mentioned this class, at least this class cannot be searched in the PHP index.
The StdClass class does not have any member methods or member attributes. After instantiation, it is an empty object.
<?php $cfg = new StdClass(); $cfg->dbhost = 'www.jb51.net'; echo $cfg->dbhost; ?>
Method 3: Toss json_encode() and json_decode()
This method is to pass an empty JSON object through json_decode()
Convert to PHP's StdClass empty object.
Similarly, you can convert an array into JSON through json_encode()
, and then convert JSON into a StdClass object through json_decode()
,
For these two functions, please refer to the PHP manual.
<?php $cfg = json_decode('{}'); $cfg->dbhost = 'www.jb51.net'; echo $cfg->dbhost; ?>
The above is the detailed content of How to use new StdClass() to create an empty object in php?. For more information, please follow other related articles on the PHP Chinese website!