2013-08-01 38 views
1

在PHP中,我發現了「解析錯誤:語法錯誤,意想不到的‘[’」在下面的代碼行:

return explode(" ", $message)[0]; 

我會提供更多的細節,但是這真的了。該行對我來說看起來無可替代,事實上它一直運行良好,直到我將它複製到另一個文件中。最大的區別是,現在這條線是一個類的一部分,它被一個我不太瞭解的大型軟件庫調用。什麼可能導致這個問題?

多一點背景:

public function getIRCCommand($message) 
{ 
    if ($message[0] != ":") 
    { 
     return explode(" ", $message)[0]; 
    } 
    else 
    { 
     return preg_split("/\s+/", $message)[1]; 
    } 
} 
+1

檢查上一行。 – pickypg

+0

@pickypg大括號。它在if語句中。 –

+1

此功能只有[在PHP 5.5中引入](http://www.php.net/manual/en/migration55.new-features.php)。你確定你沒有運行5.4或更低? – Carsten

回答

1

你可能在PHP 5.3或更低的運行。您需要升級至少PHP 5.4才能正常工作(或使用臨時變量來訪問返回數組的函數的元素)。

你在那裏做什麼叫做array dereferencing。手冊上說:

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

而且,檢查,讓我們試着運行

<?php 
echo explode(" ", "1 2 3")[1]; 

for all kinds of diferent PHP versions。結果是,PHP版本5.4和hihgher輸出「2」,這將是你想要的結果。