PHP-关联数组作为对象

PHP-关联数组作为对象

问题描述:

可能重复:
将数组转换为对象PHP

Possible Duplicate:
Convert Array to Object 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;