PHP uses new StdClass() to create empty objects

Introduction:

During the development process, PHP programmers put some information such as parameter configuration items in the array to use, but the array operation is not very convenient, many times use the object operator ->xxx than the array operator ['xxx '] It is much more convenient, so we need to create an empty object to store the required attribute name and attribute value in the object. However, PHP does not have var object = {}; such a syntax in Javascript  , so we need another way to create it.

There are 3 ways to create empty objects in PHP:

Method 1: Write an empty class

<?php
  //创建一个空类
  class Pay {
  }
  //实例化类
  $pay = new Pay;
  $pay->dbhost = 'www.zy13.net';
  echo $pay->dbhost;
?>

Method 2: Instantiate the StdClass class (recommended)

The StdClass class is a base class in PHP. The StdClass class does not have any member methods, nor any member attributes. After instantiation, it is an empty object.

<?php
  $object = new StdClass();
  $object->dbhost = 'www.zy13.net';
  echo $object->dbhost;
?>

Method 3: Empty JSON object

This method is to convert an empty JSON object json_decode()into an empty object of PHP's StdClass. In the same way, you can convert an array json_encode()to JSON, and then json_decode()convert JSON to StdClass objects.

<?php
  $object = json_decode('{}');
  $object->dbhost = 'www.zy13.net';
  echo $object->dbhost;
?>

 

Guess you like

Origin blog.csdn.net/qq15577969/article/details/113530173