PHP - 生成字符串
问题描述:
的阵列功能在我的应用程序需要很多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'
参数即可。
每个方法都有相同的逻辑,我想生成它们“动态”。我不知道这是否可能..
答
看看这个,让我知道这是你的需求与否。
$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';
}
答
发送此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"
答
你可以利用__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]);
}
给我们你希望看到当你运行功能 –
两个“吸气”方法,你看到的例子是我应该需要产生的。对于城市变量,我应该需要生成两个完全相同的方法。我更新了城市之一 – Mistre83
出于好奇,'* Attribute()'方法有什么好处?我的意思是他们所做的只是调用第二种方法。 – simon