可能的重复:
将数组转换为对象 PHP https://stackoverflow.com/questions/1869091/convert-array-to-object-php
我正在创建一个简单的 PHP 应用程序,我想使用YAML http://en.wikipedia.org/wiki/YAML文件作为数据存储。我将以关联数组的形式获取数据,例如使用以下结构:
$user = array('username' => 'martin', 'md5password' => '5d41402abc4b2a76b9719d911017c592')
但是,我想用一些函数扩展关联数组并使用->
运算符,所以我可以写这样的东西:
$user->username = 'martin'; // sets $user['username']
$user->setPassword('hello'); // writes md5 of 'hello' to $user['md5password']
$user->save(); // saves the data back to the file
有没有一种好的方法可以在没有类定义的情况下做到这一点?
基本上,我想在 PHP 中拥有 JavaScript 样式的对象:)
只需投射即可:
$user = (object)$user;
当然,还有其他更灵活的解决方案,例如创建一个实现ArrayAccess http://php.net/manual/en/class.arrayaccess.php:
$user = new User(); // implements ArrayAccess
echo $user['name'];
// could be the same as...
echo $user->name;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)