Home  >  Article  >  Backend Development  >  Sample code sharing on how to quickly create an object in PHP

Sample code sharing on how to quickly create an object in PHP

黄舟
黄舟Original
2017-10-16 09:47:211254browse

Preface

Arrays (especially associative arrays) in PHP are often used - because they are convenient. It is also common to see configuration parameters returning in array format in some frameworks. However, sometimes you may need configuration parameters of object rather than array type. After consulting network information, I found a method and recorded it.

1. Force conversion


$arr = [
    'appid' => '121434352',
    'appkey' => '19b8b372c501e1fbedead782d46199a',
    'callback' => 'http://example.com/callback.php',
    'scope' => 'add_t,add_pic_t,del_t',
    'errorReport' => true,
    'storageType' => 'file',
    'host' => 'localhost',
    'user' => 'root',
    'password' => 'root',
    'database' => 'test'
];
$obj = (Object)($arr);

2. stdClass class

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


$obj = new stdClass;
$obj->appid = '121634752';
$obj->appkey = '09bab3721ce171fbed314782d46199a';
$obj->callback = 'http://example.com/callback.php';
$obj->scope = 'add_t,add_pic_t,del_t';
$obj->errorReport = true;
$obj->storageType = 'file';
$obj->host = 'localhost';
$obj->user = 'root';
$obj->password = '';
$obj->database = 'test';

The above is the detailed content of Sample code sharing on how to quickly create an object 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