9

I have an object that looks like this:

stdClass Object
(
    [page] => stdClass Object
        (
            [1] => stdClass Object
                (
                    [element] => stdClass Object
                        (
                            [background_color] => stdClass Object
...

And when I print print_r($arr->page):

stdClass Object
(
    [1] => stdClass Object
        (
            [element] => stdClass Object
                (
                    [background_color] => stdClass Object
                        (

But this prints nothing:

print_r($arr->page->{"1"});

And this prints an error:

print_r($arr->page->1); 

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' i

How can I access the "1" element?

UPDATE:

I've also tried $arr->page[1] and $arr->page["1"] but get this error:

Fatal error: Cannot use object of type stdClass as array in

UPDATE 2:

var_dump($arr->page);

prints this:

 object(stdClass)#3 (1) {   [1]=>   
   object(stdClass)#4 (1) {
     ["element"]=>
     object(stdClass)#5 (20) {
       ["background_color"]=>
       object(stdClass)#6 (7) {
SSH This
  • 1,864
  • 4
  • 23
  • 41

2 Answers2

27

Use quotes:

print_r($arr->page->{'1'});

From here: How can I access an object attribute that starts with a number?

Community
  • 1
  • 1
Antoine
  • 2,785
  • 1
  • 16
  • 23
  • Sorry this prints nothing for me? single or double quotes – SSH This Jun 18 '13 at 01:32
  • See http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php/3446286#3446286 for the difference between single and double quotes in PHP. – BLaZuRE Jun 18 '13 at 01:38
  • 3
    This only works for string keys `"1"` vs `int(1)`. If an object was created by "illegal" means, then you cannot access the integer keys like this. – Matthew Jun 18 '13 at 01:38
11

You cannot access integer class variables directly. The best option is to not use StdClass at all.

If you cannot control the source of your data, you can cast to an array via $foo = (array) $foo.

You can also iterate over the elements:

foreach ($obj as $key=>$val)

Or

foreach (get_object_vars($obj) as $key => $val)
Matthew
  • 47,584
  • 11
  • 86
  • 98
  • Wow really, I didn't know that, I did not vote you down, I'll try to cast and the foreach – SSH This Jun 18 '13 at 01:37
  • It works! Thanks I'll have to remember this, just to clarify I used your first example there `foreach ($obj as $key=>$val)` and `$val->element` gave me access, thanks again! – SSH This Jun 18 '13 at 01:39
  • @Jack, good point. I've removed that bit from the answer. I think I was remembering times when I've dealt with sketchy libraries that blindly cast API results into an object for no good reason. – Matthew Jun 18 '13 at 01:54
  • Are you saying there was a time before `json_decode()`? *gasp* :) – Ja͢ck Jun 18 '13 at 01:54