2016-09-22 85 views
4

的陣列功能在我的應用程序需要很多getter和setter和我的想法是從陣列生成它們,例如:PHP - 生成字符串

protected $methods = ['name', 'city']; 

有了這個兩個參數,我將需要生成以下方法:

public function getNameAttribute() { 
    return $this->getName(); 
} 

public function getName($lang = null) { 
    return $this->getEntityValue('name', $lang); 
} 

而對於城市中,方法是:

public function getCityAttribute() { 
    return $this->getCity(); 
} 

public function getCity($lang = null) { 
    return $this->getEntityValue('city', $lang); 
} 

當然,我ñ eed也會生成setter(使用相同的邏輯)。你可以看到,我需要一個get<variable_name>Attribute的方法,在這個調用get<variable_name>的內部,另一個(getName)返回甚至相同的方法(對於每個getter),只需更改'name'參數即可。

每個方法都有相同的邏輯,我想生成它們「動態」。我不知道這是否可能..

+0

給我們你希望看到當你運行功能 –

+0

兩個「吸氣」方法,你看到的例子是我應該需要產生的。對於城市變量,我應該需要生成兩個完全相同的方法。我更新了城市之一 – Mistre83

+1

出於好奇,'* Attribute()'方法有什麼好處?我的意思是他們所做的只是調用第二種方法。 – simon

回答

0

看看這個,讓我知道這是你的需求與否。

$methods = ['name', 'city']; 
$func = 'get'.$methods[1].'Attribute'; 
echo $func($methods[1]); 

function getNameAttribute($func_name){ 
    $another_func = 'get'.$func_name; 
    echo 'Name: '.$another_func(); 
} 

function getCityAttribute($func_name){ 
    $another_func = 'get'.$func_name; 
    echo 'City: '.$another_func(); 
} 

function getCity(){ 
    return 'Dhaka'; 
} 

function getName(){ 
    return 'Frayne'; 
} 
0

發送此PARAMS(名稱,城市或其它)爲參數的通用方法(如果你不知道什麼PARAMS你可以得到)

public function getAttribute($value) { 
    return $this->get($value); 
} 

public function get($value, $lang = null) { 
    return $this->getEntityValue($value, $lang); 
} 

如果你知道你的參數,你可以使用這個:

public function getNameAttribute() { 
    return $this->getName(); 
} 
$value = 'Name'; //for example 
$methodName = 'get' . $value . 'Attribute'; 
$this->$methodName; //call "getNameAttribute" 
2

你可以利用__call()來做到這一點。我不打算提供一個完整的實現,但你基本上想要做的事,如:

public function __call($name, $args) { 
    // Match the name from the format "get<name>Attribute" and extract <name>. 
    // Assert that <name> is in the $methods array. 
    // Use <name> to call a function like $this->{'get' . $name}(). 

    // 2nd Alternative: 

    // Match the name from the format "get<name>" and extract <name>. 
    // Assert that <name> is in the $methods array. 
    // Use <name> to call a function like $this->getEntityValue($name, $args[0]); 
}