Home >Backend Development >PHP Tutorial >What is the use of new StdClass() in PHP

What is the use of new StdClass() in PHP

巴扎黑
巴扎黑Original
2017-08-09 15:00:362585browse

The role of new StdClass() in PHP: new StdClass() can be used to create an empty object without member methods. The syntax is: [$object = new StdClass();]. The StdClass class does not have any member methods nor any member properties.

What is the use of new StdClass() in PHP

stdClass is a base class of PHP. Almost all classes inherit this class, so it can be new at any time. Let this variable be an Object. At the same time, stdClass after instantiation does not have any properties and methods, that is, it is an empty object.

PHP can use $object = new StdClass(); to create an empty object without member methods 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, object operators->xxx are used instead of array operations. The symbol ['xxx'] is much more convenient. 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 Javascript in PHP.

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 = &#39;www.php.cn&#39;;
  echo $cfg->dbhost;
?>

Method 2: Instantiate the StdClass class

The StdClass class is a base class in PHP. However, what is strange is that it is almost never mentioned in the PHP manual. This class, at least in the PHP index, cannot be searched.

The StdClass class does not have any member methods or member attributes. It is an empty object after instantiation.

<?php
  $cfg = new StdClass();
  $cfg->dbhost = &#39;www.php.cn&#39;;
  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(&#39;{}&#39;);
  $cfg->dbhost = &#39;www.php.cn&#39;;
  echo $cfg->dbhost;
?>

For more related knowledge, please visit PHP Chinese website! !

The above is the detailed content of What is the use of new StdClass() in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn