PHP uses new StdClass () to create an empty object. newstdclass

Source: Internet
Author: User

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;?>

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.