2017-02-18 78 views
1

有沒有一種方法可以有條件地構建鏈?例如:在PHP鏈中使用Variable作爲方法來允許條件方法鏈接

$chain = $restaurant->allFoods()->$filter->get(); 

然後$filter是動態的或有條件地設置

if ($user == "vegetarian") 
{ 
    $filter = "->onlyVegetables()"; 
} 

所以,如果條件滿足,鏈將成爲:

$chain = $restaurant->allFoods()->onlyVegetables()->get(); 

其他

$chain = $restaurant->allFoods()->get(); 

是這可能嗎?這個叫什麼?謝謝

+0

你試過嗎?發生了什麼? – miken32

+0

構建動態代碼是可能的與eval,但大多數說:「eval是邪惡的」 – Sascha

回答

2

是的,通過重載方法__get/__調用,取決於你是否需要傳遞參數到過濾器或不。

<?php 
function __get($user) { 
    if($user == 'vegetarian') { 
    return $this->onlyVegetables(); 
    } 
    return $this; 
} 

http://php.net/manual/en/language.oop5.overloading.php

+0

如果我不能追加'__get()'也不'__call()'如何父模型? –

+1

您既可以擴展該類,也可以編寫包裝來實現過濾器的外觀方法。這取決於您嘗試使用的課程。 –