This article mainly introduces PHP using new StdClass () to create empty objects, combined with specific examples of the creation and use of PHP empty objects, the need for friends can refer to the following
This example describes how PHP uses new StdClass () to create an empty object. Share to everyone for your reference, as follows:
PHP can be used to $object = new StdClass();
create an empty object that has no member methods and properties.
Many times, programmers will put some information such as parameter configuration items in the array to use, but the array operation is not very convenient, many times the use of the object operator->xxx than the array operator [' xxx '] is much more convenient. You then need to create an empty object to store the required property names and property values in the object.
However, PHP does not have var object = {};
such syntax in JavaScript.
PHP to create an empty object can be implemented at least 3 ways
Method One: Write an empty class
Barely able to accomplish the task, but especially without a pattern.
<?php class cfg { } $cfg = new cfg; $cfg->dbhost = ' www.jb51.net '; echo $cfg->dbhost;? >
Method Two: Instantiate the StdClass class
The Stdclass class is a base class in PHP, but the tricky one is that the blood in the PHP manual is barely mentioned in this class, at least in the PHP index.
The Stdclass class does not have any member methods, nor any member properties, and is an empty object after instantiation.
<?php $cfg = new StdClass (); $cfg->dbhost = ' www.jb51.net '; echo $cfg->dbhost;? >
Method Three: Toss Json_encode () and Json_decode ()
This approach is to transform an empty JSON object into a json_decode()
php stdclass empty object.
In the same way, you can turn an array json_encode()
into JSON, and then convert json_decode()
the JSON to a Stdclass object,
For these two functions, refer to the PHP manual.
<?php $cfg = Json_decode (' {} '); $cfg->dbhost = ' www.jb51.net '; echo $cfg->dbhost;? >