Reputation: 5796
From PHP 5.4, I can call an element of a function returned array, like so: func()['el']
.
I'm running PHP 5.6 and test the following (simplified) code:
$decoded = json_decode($content, true)['foo'];
($decoded = json_decode($content, true))['foo']; // syntax error ['
I don't understand why I cannot assign json_decode($content, true)
to $decoded
and call the element foo
immediately. This works fine in php 7
My PhpStorm 2017.2.1, with applied php 5.6 DOESN'T detect this code as available in PHP 7 only!
Upvotes: 1
Views: 60
Reputation: 17417
One of the many features that PHP 7 introduced was an Abstract Syntax Tree. This directly led to more complex expressions being possible, such as the one in your question.
Simply, the change is that a function return wrapped in brackets previously did not behave the same as one that is not:
<?php
function foo() { return ['a' => 'b']; }
echo foo()['a']; // Works in PHP 5.4+
echo (foo())['a']; // Works in PHP 7+
Functional array dereferencing, as you mention, was added in 5.4, but only as a special case in the parser. In PHP 7+, you can dereference any expression that yields an array.
Upvotes: 3