PHP - associative array as an object(PHP - 作为对象的关联数组)
问题描述
可能重复:
将数组转换为PHP对象
我正在创建一个简单的 PHP 应用程序,我想使用 YAML 文件作为数据存储.我将数据作为关联数组获取,例如以下结构:
I'm creating a simple PHP application and I would like to use YAML files as a data storage. I will get the data as an associative array, with this structure for example:
$user = array('username' => 'martin', 'md5password' => '5d41402abc4b2a76b9719d911017c592')
但是,我想用一些函数来扩展关联数组并使用 ->
运算符,所以我可以这样写:
However, I would like to extend the associative array with some functions and use the ->
operator, so I can write something like this:
$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
在没有类定义的情况下,有没有一种好方法可以做到这一点?
Is there a good way to do this without a class definition?
基本上,我想在 PHP 中使用 JavaScript 样式的对象 :)
Basically, I would like to have JavaScript style objects in PHP :)
推荐答案
投吧:
$user = (object)$user;
当然,还有其他更灵活的解决方案,例如创建一个实现 数组访问
:
Of course, there are other, more flexible solutions like creating a class that implements ArrayAccess
:
$user = new User(); // implements ArrayAccess
echo $user['name'];
// could be the same as...
echo $user->name;
这篇关于PHP - 作为对象的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP - 作为对象的关联数组


- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Laravel 仓库 2022-01-01