PHP uses new StdClass () to create an empty object. newstdclass
This example describes how PHP uses new StdClass () to create an empty object. We will share this with you for your reference. The details are as follows:
PHP can be used$object = new StdClass();
Create an empty object without Member methods and attributes.
In many cases, programmers put some information such as parameter configuration items in an array, but array operations are not very convenient, the object operator> xxx is much more convenient than the array operator ['xxx. Therefore, you need to create an empty object to store the required attribute names and attribute values to the object.
However, PHP does not contain Javascript.var object = {};
This syntax.
PHP can create an empty object in at least three ways.
Method 1: Write an empty class
The task is barely completed, but it is not in a 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 it is strange that the class is hardly mentioned in the PHP manual. At least this class cannot be found in the PHP index.
The StdClass class does not have any member methods or any member attributes. It is an empty object after instantiation.
<?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 throughjson_decode()
To an empty StdClass object of PHP.
In the same way, you can use an arrayjson_encode()
Convert to JSON, and then usejson_decode()
Convert JSON to StdClass object,
For more information about these two functions, see the PHP manual.
<?php $cfg = json_decode('{}'); $cfg->dbhost = 'www.jb51.net'; echo $cfg->dbhost;?>