Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Object with Key as Number PHP [duplicate]

Tags:

object

oop

php

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) {
like image 435
SSH This Avatar asked Jun 18 '13 01:06

SSH This


2 Answers

Use quotes:

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

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

like image 125
Antoine Avatar answered Nov 01 '22 14:11

Antoine


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)
like image 10
Matthew Avatar answered Nov 01 '22 13:11

Matthew