PHP __call并生成函数名称

时间:2014-08-01 18:11:39

标签: php

如何使用__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

2 个答案:

答案 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
    );
}

<强>文档

答案 1 :(得分:0)

它不一定&#34;生成&#34;方法,但您可以使用__call()

动态调用这些方法
public function __call($name, $arguments)
{
    $method = $name . ucfirst($arguments[1]);
    return $this->$method($arguments[0]);
}