23

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 :)

3
  • 4
    Should use at least sha1 these days. Commented Aug 30, 2012 at 18:22
  • 2
    +wesside 2016 update: BCrypt via password_hash or PBKDF2 with SHA512. Commented Jan 8, 2016 at 15:29
  • @mjsa way to look out! Commented Aug 11, 2017 at 17:06

2 Answers 2

53

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Note that if $user is null, casting it to (object) will make it non-null (it will be an empty object). To avoid this you can do this: $user = $user ? (object)$user : null
9

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

1 Comment

Note this will also convert sequential (non-associative) arrays to objects as well. You might want to combine with this answer: stackoverflow.com/a/4254008/1074400

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.