2016-05-10 40 views
0

我有這個問題:我想連接更多的方法,但我需要一個方法(第一個),如果有另一個方法後,返回$ this,否則返回一個對象。OOP:方法連接並檢查「隊列」

例子:

$some->create('Foo')->with('Bar'); 
$some->create('Foo'); 

在第一個例子,$some->create()必須返回$此允許的連接。 在第二種方法中,create()必須返回一個對象。

有沒有辦法改變方法順序?現在我總是返回$ this,然後您可以使用另一個函數獲取該對象「返回」(例如:$some->create('Foo')->getInfo();

謝謝。

+0

這就是所謂的**方法chainig **。 –

+0

這沒有幫助。問題是另一個。我知道如何做方法鏈,但我不知道如何(如果有可能)返回不同的值,如果在第一個之後有另一個方法。 – Grork

+2

代碼從左到右評估,所以'create()'方法永遠不會知道有一個額外的方法調用'with()',它會在被調用後執行 –

回答

1

您的方法create()可能會返回任何內容,但沒有關於調用方法對它做什麼的信息。 可能的選項是傳遞可選參數或使用包裝器方法。

class Test { 
    public function create($what, $methodChaining = false) 
    { 
     // do stuff, create $object 
     if ($methodChaining) { 
      return $this; 
     } 
     return $object; 
    } 

    public function createAndChain($what) 
    { 
     $this->create($what); 
     return $this; 
    } 
} 

$object->create('Foo', true)->with('Bar'); // execute with() on the first $object 
$object->createAndChain('Foo')->with('Bar'); // same as above 
$object->create('Foo')->with('Bar'); // execute with() from the new Foo-object 

此外,該代碼無法知道,如果要執行的第一個對象或創建一個新的鏈接的方法..