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:
$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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With