Home > Article > Backend Development > Sample code sharing on how to quickly create an object in PHP
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.
$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);
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!