PHP - associative array as an object [duplicate]

2019-03-18 13:28发布

问题:

Possible Duplicate:
Convert Array to Object PHP

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?

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

回答1:

Just cast it:

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


回答2:

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.

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;
    }