How to access object properties with names like integers?

后端 未结 7 961
故里飘歌
故里飘歌 2020-11-21 22:14

I am using json_decode() something like:

$myVar = json_decode($data)

Which gives me output like this:

[highlig         


        
7条回答
  •  眼角桃花
    2020-11-21 23:10

    For PHP 7

    Accessing Object properties having numbers as property name. Mostly needed after casting array to object.

        $arr = [2,3,7];
        $o = (object) $arr;
    
        $t = "1";
        $t2 = 1;
        $t3 = (1);
    
        echo $o->{1};      // 3
        echo $o->{'1'};   // 3
        echo $o->$t;        // 3
        echo $o->$t2;       // 3
        echo $o->$t3;       // 3
    
        echo $o->1;       // error
        echo $o->(1);      // error
    

提交回复
热议问题