关联数组作为对象

关联数组作为对象

本文介绍了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-关联数组作为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:24