Search code examples
phpoperators

What does PHP operator ->{...} mean?


I recently saw this line in a PHP piece of code:

$dbObject = json_decode($jsonString);
$dbObject->{'mysql-5.4'}[0]->credentials

What does this mean? In the PHP docs we can read, that

Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

But how can the Object $dbObject be defined to allow ->{...}[...]access? Is this code kind of unsafe? Which PHP version does allow this?

Did I miss anything in the PHP docs?


Solution

  • It's to enable access to properties which would be invalid syntax as bare literals. Meaning:

    $dbObject->mysql-5.4[0]->credentials
    

    This is invalid/ambiguous syntax. To make clear to PHP that mysql-5.4 is a property and not a property minus a float, you need to use the {'..'} syntax.

    To be exact, ->{..} enables you to use any expression as the property name. For example:

    $dbObject->{ sprintf('%s-%.1f', 'mysql', 5.4) }