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

前端 未结 2 1182
醉梦人生
醉梦人生 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

    There are multiple ways, the problem is that the PHP tokenizer will choke on the - sign in the code, howver you can write it so that the parser does not complains:

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

    or

    $property = 'pre-selection'
    echo $object->$property;
    

    or

    $array = (array) $object;   
    echo $array['pre-selection'];
    

    In these cases, the PHP parser does not run about a place in the raw code that it has a problem to parse with any longer.


    Wondering where this is documented. For example in the SimpleXML documentation:

    Accessing elements within an XML document 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.

    Example #3 Getting

    movie->{'great-lines'}->line;
    ?>
    

    The above example will output:

    PHP solves all my web problems
    

提交回复
热议问题