tags:

views:

381

answers:

4

In PHP, you can initialize arrays with values quickly using the following notation:

$array = array("name" => "member 1", array("name" => "member 1.1") ) ....

is there any way to do this for STDClass objects? I don't know any shorter way than the dreary

$object = new STDClass();
$object->member1 = "hello, I'm 1";
$object->member1->member1 = "hello, I'm 1.1";
$object->member2 = "hello, I'm 2";
+13  A: 

You can use type casting:

$object = (object) array("name" => "member 1", array("name" => "member 1.1") );
Gumbo
While I'd personally suggest actually making your classes do something, and using arrays as "dumb containers", this is the way to do it.
Jani Hartikainen
Jani, you have a point, but I just *love* addressing containers the -> way. :)
Pekka
Cheers, I didn't know it was that easy - at least for one-dimensional ones.
Pekka
+1  A: 

Here's a post showing both type casting and using a recursive function to convert single and multi-dimensional arrays to a standard object.

Tim Lytle
I asked for multi-dimensional arrays, so this is it. Thanks.
Pekka
For the moment, I will work with type casting only. On the long run, I will go for a mix between gnud's and this answer: A dumb_container object that can work recursively. Thanks all.
Pekka
+3  A: 

You could try:

function initStdClass($thing) {
    if (is_array($thing)) {
      return (object) array_map(__FUNCTION__, $thing);
    }
    return $thing;
}
outis
Use `__FUNCTION__` for more flexibility.
Gumbo
Done.                                                        


‬ ⁡⁢⁣⁠⁠⁠⁡
outis
+1  A: 

I use a class I name Dict:

class Dict {

    public function __construct($values = array()) {
        foreach($values as $k => $v) {
            $this->{$k} = $v;
        }
    }
}

It also has functions for merging with other objects and arrays, but that's kinda out of the scope of this question.

gnud