PHP Array Syntax Parse Error Left Square Bracket "["

I have a function that returns an array. I have another function that just returns the first row, but for some reason, it makes me use an intermediate variable, ie this fails:

function f1(/*some args*/) {
    return /*an array*/;
}
function f2(/*some args*/) {
    return f1(/*some args*/)[0];
}

. . . with:

Parse error: syntax error, unexpected '[' in util.php on line 10

But, this works:

function f1(/*some args*/) {
    return /*an array*/;
}
function f2(/*some args*/) {
    $temp = f1(/*some args*/);
    return $temp[0];
}

I wasn't able to find anything pertinent online (my searches kept getting confused by people with "?", "{", "<", etc.).

I'm self-taught in PHP - is there some reason why I can't do this directly that I've missed?


You can't use function array dereferencing

return f1(/*some args*/)[0];

until PHP 5.4.0 and above.


The reason for this behavior is that PHP functions can't be chained like JavaScript functions can be. Just like document.getElementsByTagNames('a')[0] is possible.

You have to stick to the second approach for PHP version < 5.4

Function array dereferencing has been added, eg foo()[0].

http://php.net/manual/en/migration54.new-features.php

链接地址: http://www.djcxy.com/p/11956.html

上一篇: PHP 5.6.3解析错误:语法错误,在类中出现意外的'[''

下一篇: PHP数组语法分析错误左方括号“[”