How to access an object property with a minus-sign?

前端 未结 2 1183
醉梦人生
醉梦人生 2020-12-11 01:46

I got an object (in PHP) and I can\'t print the content. In debug-mode it\'s like this:

stdClass Object
(
    [pre-selection] => 1
)

But

2条回答
  •  心在旅途
    2020-12-11 02:35

    You could try

    $object->{'pre-selection'};
    

    http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

    See also Example 2 of json_decode()

    Example #2 Accessing invalid object properties

    Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

    {'foo-bar'}; // 12345
    
    ?>
    

    Update (thanks to salathe):

    Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid

提交回复
热议问题