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 :)
Just cast it:
Of course, there are other, more flexible solutions like creating a class that implements
ArrayAccess
: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: