如何使用__cal
生成函数名称?
示例:
public function setTitleEn($title){
$this->titleEn = $title;
}
public function setTitleDe($title){
$this->titleDe = $title;
}
public function setBodyEn($body){
$this->bodyEn = $body;
}
public function setBodyDe($body){
$this->bodyDe = $body;
}
public function __call($name, $arguments)
{
//execution function
}
$article = new Article();
$article->setTitle("My title", "en") //execution setTitleEn
$article->setTitle("My title", "de") //execution setTitleDe
$article->setBody("My title", "de") //execution setBodyEn
等
答案 0 :(得分:0)
使用call_user_func_array
。你必须在这里建立一些假设,比如最终的论证总是被视为语言。
public function __call($name, $arguments) {
$lang = 'en';
if (count($arguments) > 1)
$lang = array_shift($arguments);
$fname = $name.ucwords($lang);
if (method_exists($this, $fname) === false) {
throw new Exception('Method "'.$name.'" does not exist.');
}
return call_user_func_array(
array($this, $fname),
$arguments
);
}
<强>文档强>
call_user_func_array
- http://php.net/manual/en/function.call-user-func-array.php method_exists
- http://php.net/manual/en/function.method-exists.php 答案 1 :(得分:0)
它不一定&#34;生成&#34;方法,但您可以使用__call()
动态调用这些方法public function __call($name, $arguments)
{
$method = $name . ucfirst($arguments[1]);
return $this->$method($arguments[0]);
}