22

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

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

$user = array('username' => 'martin', 'md5password' => '5d41402abc4b2a76b9719d911017c592')

但是,我想用一些函数扩展关联数组并使用->运算符,所以我可以写这样的东西:

$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

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

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

4

2 回答 2

50

只需投射它:

$user = (object)$user;

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

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

echo $user['name'];
// could be the same as...
echo $user->name;
于 2012-08-30T18:25:26.000 回答
8

从字面上看,只需制作一个$class = new stdClass;并迭代和重新分配。请注意,这只是一层深度,就像类型转换一样。您必须编写一个递归迭代器才能得到它。据我所知,Kohana 2/3 有 to_object() 你可能可以使用。

找到了:

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;
    }
于 2012-08-30T18:24:27.020 回答