PHP - 作为对象的关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12203074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:02:08  来源:igfitidea点击:

PHP - associative array as an object

phpclassobjectyamlassociative-array

提问by Martin Majer

Possible Duplicate:
Convert Array to Object PHP

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

I'm creating a simple PHP application and I would like to use YAMLfiles as a data storage. I will get the data as an associative array, with this structure for example:

我正在创建一个简单的 PHP 应用程序,我想使用YAML文件作为数据存储。我将数据作为关联数组获取,例如使用以下结构:

$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?

在没有类定义的情况下,有没有一种好方法可以做到这一点?

Basically, I would like to have JavaScript style objects in PHP :)

基本上,我想在 PHP 中有 JavaScript 样式的对象:)

回答by FtDRbwLXw6

Just cast it:

只需投射它:

$user = (object)$user;

Of course, there are other, more flexible solutions like creating a class that implements ArrayAccess:

当然,还有其他更灵活的解决方案,例如创建一个实现的类ArrayAccess

$user = new User(); // implements ArrayAccess

echo $user['name'];
// could be the same as...
echo $user->name;

回答by wesside

Literally just make a $class = new stdClass;and iterate and reassign. Be aware this is only one level deep, just like typecasting. You would have to write a recursive iterator to get it all. From what I remember Kohana 2/3 has to_object() you can probably use.

字面上只是制作一个$class = new stdClass;并迭代和重新分配。请注意,这只是一层深度,就像类型转换一样。你将不得不编写一个递归迭代器来获得这一切。从我记得 Kohana 2/3 有 to_object() 你可能可以使用。

Found it:

找到了:

class Arr extends Kohana_Arr {

    public static function to_object(array $array, $class = 'stdClass')
    {
            $object = new $class;
            foreach ($array as $key => $value)
            {
                    if (is_array($value))
                    {
                    // Convert the array to an object
                            $value = arr::to_object($value, $class);
                    }
                    // Add the value to the object
                    $object->{$key} = $value;
            }
            return $object;
    }