2017-04-11 19 views
-2

我搜索一下PHP方法鏈和所有的教程可以在網絡上使用的「返回$此」的方法鏈接。PHP方法鏈接,而無需編寫大量的回報這

有一個神奇的方法或庫,可以使用幫助鏈接一個類的方法,而無需編寫在每一個方法的終結「這回$」。

+0

不存在;除非你使用魔法調用,這不是一個好主意......你在每種方法結束時返回的問題是什麼? –

+0

可能在PHP 7.2中的新功能(https://wiki.php.net/rfc/pipe-operator) – Xorifelse

+0

@MarkBaker這是我寫的太多了回報$這對我的圖書館 – nonsensecreativity

回答

2

在語言本身是沒有辦法實現這一點沒有return $this。沒有指定返回值的函數和方法將在PHP中返回null,如文檔中所述:http://php.net/manual/en/functions.returning-values.php

由於null不是具有可調用方法的對象,因此在調用鏈中的下一項時會引發錯誤。

你的IDE可能會出現一些功能,使得重複性的任務更容易完成,就像使用片段或正則表達式查找和替換。但除此之外,語言本身目前要求你設計你的班級以便在鏈接上流利地使用,或者專門設計它不是。


編輯1

我想你可以想見,使用魔法的方法來實現這樣的「自動神奇地」。我會建議反對它,因爲它是一個可憐的範例,但這並不意味着你不能使它工作。

我的想法是,你可以我們__call魔術方法來包裝你的實際方法(http://php.net/manual/en/language.oop5.overloading.php#object.call)。

<?php 

class Whatever 
{ 
    public function __call($method, $parameters) 
    { 
     //If you're using PHP 5.6+ (http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list) 
     $this->$method(...$parameters); 

     //If using < PHP 5.6 
     call_user_func_array(array($this, $method), $parameters); 

     //Always return self 
     return $this; 
    } 

    //Mark methods you want to force chaining on to protected or private to make them inaccessible outside the class, thus forcing the call to go through the __call method 
    protected function doFunc($first, $second) 
    { 
     $this->first = $first; 
     $this->second = $second; 
    } 
} 

所以我認爲這是可能的,但同樣我個人認爲,一個神奇的解決方案,而有效的,散發出顯著代碼味道,並有可能使其更好地只是處理輸入return $this在那裏你打算,通過您的設計,以允許鏈接。

+0

如果你打算兼容5.6以下的兼容性,我只想在'[]'上使用'array()'。 – Xorifelse

+0

好點 - 方括號對任何小於5.4的東西都會造成致命一擊。我會改變這一點,以使評論準確。 – stratedge

+0

我認爲片段更好。我想在做單元測試時避免將來出現問題等 – nonsensecreativity