【问题标题】:PHP - associative array as an object [duplicate]PHP - 作为对象的关联数组[重复]
【发布时间】:2012-08-25 13:08:05
【问题描述】:

可能重复:
Convert Array to Object 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 样式对象 :)

【问题讨论】:

  • 这些天至少应该使用 sha1。
  • +wesside 2016 更新:BCrypt 通过 password_hash 或带有 SHA512 的 PBKDF2。
  • @mjsa 看看!

标签: php class object yaml associative-array


【解决方案1】:

实际上只需创建一个$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;
    }

【讨论】:

【解决方案2】:

只要施放它:

$user = (object)$user;

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

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

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

【讨论】:

  • 请注意,如果 $user 是 null,将其转换为 (object) 将使其非空(它将是一个空对象)。为避免这种情况,您可以这样做:$user = $user ? (object)$user : null
猜你喜欢
  • 2012-08-30
  • 2017-10-26
  • 2023-04-07
  • 2018-03-30
  • 1970-01-01
  • 2011-05-19
相关资源
最近更新 更多