How to access php curly brace object property [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-01 03:43:58

问题


Possible Duplicate:
How to access object properties with names like integers?

print_r($myObj) gives the following result:

stdClass Object
(
    [4021450] => stdClass Object
    (
        [property1] => ooo
        [property2] => xxx
    )
    [3971601] => stdClass Object
    (
        [property1] => 123
        [property2] => 356
    )
)

How can I using the curly brace syntax with variable to access the sub-object?

I tried:

$myObj->'3971601';                     // Parse error: syntax error  
$myObj->{'3971601'};                   // Works  
$id = 3971601; $myObj->{$id};          // Notice: Trying to get property of non-object  
$id = 3971601; $myObj->{''.$id};       // Notice: Trying to get property of non-object  
$arr = (array)$myObj; $arr[3971601];   // Notice: Undefined offset: 3971601
$arr = (array)$myObj; $arr['3971601']; // Notice: Undefined index: 3971601

回答1:


You should be able to omit the curly braces entirely: $myObj->$id. Your last 4 examples, however, indicate something is amiss. It seems somewhere along the lines, $myObj was set null or to some other non-object value.



来源:https://stackoverflow.com/questions/4643894/how-to-access-php-curly-brace-object-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!