2012-12-28 47 views
3

我很驚訝,當我錯誤地輸入什麼,我相信會引發錯誤:函數鏈接結果?從什麼時候這是可能的?

function r() { return array('foo'); } 
echo r()[0]; 

令我驚訝的是,它的工作,甚至沒有提出一個通知。我記得我第一次嘗試時無法做到這一點,我注意到在Codepad an error was raised上。我正在運行PHP 5.4.4,並且想知道何時添加了這個功能,以及我可以在哪裏閱讀更多內容。谷歌只顯示PHP 5方法鏈接的結果,但我想這是別的?

+0

從[array docs](http://php.net/manual/en/language.types.array.php):*「從PHP 5.4開始,可以對函數的結果進行數組解引用或方法直接調用,之前只能使用臨時變量。「*你也可以在這裏閱讀更多關於它的內容(沒有太多,實際上沒有什麼特別的)。 –

+0

謝謝,現在我可以放心,我沒有偶然發現一些奇怪的bug,並在代碼中留下這樣的bug。 ;) –

回答

3

自PHP 5.4,它可能「陣列解引用」函數/直接方法的結果;在PHP 5.5,同樣也適用於數組文本(array('foo', 'bar')[1];甚至[1,2,3][1];,雖然我不知道後者)

See the docs here
例7數組語法:

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.

編輯:
只是要清楚:方法鏈確實是別的;它通常也被稱爲「流暢的界面」。至少在我以前的工作中,每個人都這樣稱呼它。基本思想是不需要返回任何東西的方法得到一個明確的return $this;聲明。其結果是,這些方法返回的對象,你可以用它來調用其他方法的引用,而不必鍵入VAR第二次:

$someObject->setProperty('Foobar')//returns $this 
      ->anotherMethod(); 
//instead of 
$someObject->setProperty('Foobar');//returns null by default 
$someObject->anotherMethod(); 

此對象的代碼是這樣的:

class Foo 
{ 
    private $properties = null; 

    public function __construct(array $initialProperties = array()) 
    { 
     $this->properties = $initialProperties; 
    } 
    //chainable: 
    public function setProperty($value) 
    { 
     $this->properties[] = $value; 
     return $this;//<-- that's all 
    } 
    //NOT chainable 
    public function anotherMethod() 
    { 
     return count($this->properties);//or something 
    } 
} 
相關問題