2

Why is it that in PHP 5.3.8:

$obj->foo()['bar']; // syntax error
$obj->foo()->['bar']; // valid

But in PHP 5.4.9 it's reverse:

$obj->foo()['bar']; // valid
$obj->foo()->['bar'] // syntax error

4 Answers4

2

$obj->foo()['bar']; is valid in PHP >= 5.4.0

$obj->foo()->['bar'] is not valid in any version even if you add the required ;

So in versions before 5.4.0 you will get a parse error on the first line that will stop execution and not show the parse error on the next line.

In versions 5.4.0 and greater the first line works but you get a parse error on the second. So if you reverse them, you will always get the parse error for $obj->foo()->['bar'] in any version.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
2

Example $obj->foo()->['bar'] was never valid, in any PHP version; see here.

Maybe you got it mistaken with syntax like $obj->foo()->{'bar'}; see here.

Example $obj->foo()['bar'] is valid from PHP >= 5.4.0; see here.

Glavić
  • 42,781
  • 13
  • 77
  • 107
0

Your first example has never been valid.

$obj->foo()->['bar']; // is invalid in any PHP implementation 

However with method chaining support: if $obj->foo() returns an object with a bar property this will work:

$obj->foo()->bar;
hammus
  • 2,602
  • 2
  • 19
  • 37
0

Support for

$obj->foo()['bar'];

came in PHP 5.4.0 as support for function array dereferencing was added only from that version.

This useful page explains it: https://wiki.php.net/rfc/functionarraydereferencing

sherwoor
  • 185
  • 6