PHP에 대해 동일한 클래스에서 동적으로 메소드를 호출하는 방법이 있습니까? 구문이 맞지 않지만 다음과 비슷한 작업을 수행하려고합니다.
$this->{$methodName}($arg1, $arg2, $arg3);
PHP에 대해 동일한 클래스에서 동적으로 메소드를 호출하는 방법이 있습니까? 구문이 맞지 않지만 다음과 비슷한 작업을 수행하려고합니다.
$this->{$methodName}($arg1, $arg2, $arg3);
답변:
이를 수행하는 방법은 여러 가지가 있습니다.
$this->{$methodName}($arg1, $arg2, $arg3);
$this->$methodName($arg1, $arg2, $arg3);
call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));
리플렉션 API http://php.net/manual/en/class.reflection.php를 사용할 수도 있습니다 .
call_user_func_array당신을위한 것입니다.
call_user_func_array($this->$name, ...)왜 작동하지 않을지 궁금했습니다!
PHP에서 오버로딩을 사용할 수 있습니다 : 오버로딩
class Test {
private $name;
public function __call($name, $arguments) {
echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);
//do a get
if (preg_match('/^get_(.+)/', $name, $matches)) {
$var_name = $matches[1];
return $this->$var_name ? $this->$var_name : $arguments[0];
}
//do a set
if (preg_match('/^set_(.+)/', $name, $matches)) {
$var_name = $matches[1];
$this->$var_name = $arguments[0];
}
}
}
$obj = new Test();
$obj->set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String
echo $obj->get_name();//Echo:Method Name: get_name Arguments:
//return: Any String
수년이 지난 후에도 여전히 유효합니다! 사용자 정의 콘텐츠 인 경우 $ methodName을 잘라야합니다. $ this-> $ methodName에 선행 공백이 있음을 알 때까지 작동하지 못했습니다.
클로저를 사용하여 단일 변수에 메서드를 저장할 수 있습니다.
class test{
function echo_this($text){
echo $text;
}
function get_method($method){
$object = $this;
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
}
$test = new test();
$echo = $test->get_method('echo_this');
$echo('Hello'); //Output is "Hello"
편집 : 코드를 편집했으며 이제 PHP 5.3과 호환됩니다. 여기에 또 다른 예