PHP - 作为对象的关联数组

2022-01-14 00:00:00 class object yaml php associative-array

可能重复:
将数组转换为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;

相关文章