How do I use new StdClass () to create an empty object in PHP?

Source: Internet
Author: User
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;? >
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.