1

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:

Works

$decoded = json_decode($content, true)['foo'];

Doesn't Work

($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

Why this is Interesting?

My PhpStorm 2017.2.1, with applied php 5.6 DOESN'T detect this code as available in PHP 7 only!

5
  • cannot reproduce : 3v4l.org/b8Q0R. You might not be running the php version you think you are. Commented Oct 4, 2017 at 8:07
  • I think your json $content has some issue, can you share $conent Commented Oct 4, 2017 at 8:10
  • 1
    ($decoded = json_decode($content, true))['foo']; syntax is not correct for 5.6. have a look at 3v4l.org/v3Tqt Commented Oct 4, 2017 at 8:12
  • @ChetanAmeta I know, but that's the last part of my question Commented Oct 4, 2017 at 8:21
  • I added a section to my question about PhpStorm. Commented Oct 4, 2017 at 8:28

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.