Home >Backend Development >PHP Tutorial >How to quickly create an object in PHP

How to quickly create an object in PHP

一个新手
一个新手Original
2017-10-14 10:22:073606browse

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' => '101434352',
    'appkey' => '09b8b372150171fbede71d782d46199a',
    'callback' => 'http://test.nbycc.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, and almost all classes inherit it This class, so it can be new at any time, making 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 = '101434352';
$obj->appkey = '09b8b372150171fbede71d782d46199a';
$obj->callback = 'http://test.nbycc.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 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