Home » Php » oop – Accessing Object with Key as Number PHP

oop – Accessing Object with Key as Number PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

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) {
How to&Answers:

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)

Answer:

Use quotes:

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

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