mingc

前言

PHP 中的数组(尤其关联数组)是经常使用的 —— 因为方便。在一些框架中也经常见到返回数组格式的配置参数。然而有些时候可能需要对象而非数组类型的配置参数,在查阅网络资料后找到了方法,作以记录。

 

1. 强制转换

$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类

stdClass 是 PHP 的一个基类,几乎所有的类都继承了这个类,所以任何时候都可以被 new,让这个变量成为一个 Object。同时,实例化之后的 stdClass 是没有任何属性和方法的,也就是一个空对象。

$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\';

  

参考链接:

转] php“对象,数组”互相转换

PHP中的stdClass 【转】

分类:

技术点:

相关文章:

  • 2021-10-20
  • 2021-05-09
  • 2021-12-12
  • 2021-10-20
  • 2021-09-27
  • 2021-12-21
  • 2021-11-16
猜你喜欢
  • 2021-12-07
  • 2021-10-20
  • 2021-06-09
  • 2021-11-06
  • 2021-09-03
  • 2021-10-20
相关资源
相似解决方案