PHP - 作为对象的关联数组

PHP - associative array as an object(PHP - 作为对象的关联数组)
本文介绍了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 - 作为对象的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)