37

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";
4
  • you should change the "correct tick" from Tim to the answer of Dumbo Commented Aug 25, 2012 at 15:09
  • 2
    @mrzmyr, dumbo or gumbo? Commented Jul 27, 2013 at 12:59
  • @Pacerier sorry, i meant Gumbo :) Commented Jul 27, 2013 at 16:38
  • I tend to make a static ::fromArray(...) method which can instantiate and return new instances, or arrays of them. Commented Jul 21, 2023 at 9:25

8 Answers 8

56

You can use type casting:

$object = (object) array("name" => "member 1", array("name" => "member 1.1") );
Sign up to request clarification or add additional context in comments.

5 Comments

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, you have a point, but I just love addressing containers the -> way. :)
Cheers, I didn't know it was that easy - at least for one-dimensional ones.
@Gumbo, This wouldn't work above 1D. Simplest solution is to write our own function that expands it.
This should probably also have (object) before the second array. See @nickl-'s answer.
31

I also up-voted Gumbo as the preferred solution but what he suggested is not exactly what was asked, which may lead to some confusion as to why member1o looks more like a member1a.

To ensure this is clear now, the two ways (now 3 ways since 5.4) to produce the same stdClass in php.

  1. As per the question's long or manual approach:

    $object = new stdClass;
    $object->member1 = "hello, I'm 1";
    $object->member1o = new stdClass;
    $object->member1o->member1 = "hello, I'm 1o.1";
    $object->member2 = "hello, I'm 2";
    
  2. The shorter or single line version (expanded here for clarity) to cast an object from an array, ala Gumbo's suggestion.

    $object = (object)array(
         'member1' => "hello, I'm 1",
         'member1o' => (object)array(
             'member1' => "hello, I'm 1o.1",
         ),
         'member2' => "hello, I'm 2",
    );
    
  3. PHP 5.4+ Shortened array declaration style

    $object = (object)[
         'member1' => "hello, I'm 1",
         'member1o' => (object)['member1' => "hello, I'm 1o.1"],
         'member2' => "hello, I'm 2",
    ];
    

Will both produce exactly the same result:

stdClass Object
(
    [member1] => hello, I'm 1
    [member1o] => stdClass Object
        (
            [member1] => hello, I'm 1o.1
        )

    [member2] => hello, I'm 2
)

nJoy!

2 Comments

Excellent summary. Good to note the member1o needs to be different from the memeber1 string
Thanks for the thorough summary. Hopefully, this gets accepted!
9

From a (post) showing both type casting and using a recursive function to convert single and multi-dimensional arrays to a standard object:

<?php
function arrayToObject($array) {
    if (!is_array($array)) {
        return $array;
    }
  
    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
        foreach ($array as $name=>$value) {
            $name = strtolower(trim($name));
            if (!empty($name)) {
                $object->$name = arrayToObject($value);
            }
        }
        return $object;
    }
    else {
        return FALSE;
    }
}

Essentially you construct a function that accepts an $array and iterates over all its keys and values. It assigns the values to class properties using the keys.

If a value is an array, you call the function again (recursively), and assign its output as the value.

The example function above does exactly that; however, the logic is probably ordered a bit differently than you'd naturally think about the process.

4 Comments

I asked for multi-dimensional arrays, so this is it. Thanks.
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.
Can you expand this answer to here? The link could've been dead.
The Link is in fact dead!
6

You can use :

$object = (object)[]; // shorter version of (object)array();

$object->foo = 'bar';

Comments

5

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.

Comments

5

You could try:

function initStdClass($thing) {
    if (is_array($thing)) {
      return (object) array_map(__FUNCTION__, $thing);
    }
    return $thing;
}

1 Comment

Use __FUNCTION__ for more flexibility.
4

from this answer to a similar question:

As of PHP7, we have Anonymous Classes which would allow you to extend a class at runtime, including setting of additional properties:

$a = new class() extends MyObject {
    public $property1 = 1;
    public $property2 = 2;
};

echo $a->property1; // prints 1

It's not as succinct as the initializer for array. Not sure if I'd use it. But it is another option you can consider.

Comments

2

Another option for deep conversion is to use json_encode + json_decode (it decodes to stdClass by default). This way you won't have to repeat (object) cast in each nested object.

$object = json_decode(json_encode(array(
     'member1' => "hello, I'm 1",
     'member1o' => array(
         'member1' => "hello, I'm 1o.1",
     ),
     'member2' => "hello, I'm 2",
)));

output:

php > print_r($object);
stdClass Object
(
    [member1] => hello, I'm 1
    [member1o] => stdClass Object
        (
            [member1] => hello, I'm 1o.1
        )

    [member2] => hello, I'm 2
)

1 Comment

But empty arrays are still treated as arrays, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.