반응형
PHP에서 동적 클래스 메서드 호출
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를 사용할 수도 있습니다 .
중괄호를 생략하십시오.
$this->$methodName($arg1, $arg2, $arg3);
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
또한 사용할 수 있습니다 call_user_func()
및call_user_func_array()
PHP의 클래스 내에서 작업하는 경우 PHP5에서 오버로드 된 __call 함수를 사용하는 것이 좋습니다. 여기 에서 참조를 찾을 수 있습니다 .
기본적으로 __call은 OO PHP5의 변수에 대해 __set 및 __get이 수행하는 작업을 동적 함수에 대해 수행합니다.
이 모든 세월이 지난 후에도 여전히 유효합니다! 사용자 정의 콘텐츠 인 경우 $ methodName을 잘라야합니다. $ this-> $ methodName에 선행 공백이 있음을 알 때까지 작동하지 못했습니다.
나의 경우에는.
$response = $client->{$this->requestFunc}($this->requestMsg);
PHP SOAP 사용.
클로저를 사용하여 단일 변수에 메서드를 저장할 수 있습니다.
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과 호환됩니다. 여기에 또 다른 예
참고 URL : https://stackoverflow.com/questions/251485/dynamic-class-method-invocation-in-php
반응형
'code' 카테고리의 다른 글
컴파일러는 여기서 무엇을합니까 : int a = b * (c * d * + e)? (0) | 2020.10.23 |
---|---|
컨테이너 이름에서 도커 컨테이너 ID 가져 오기 (0) | 2020.10.23 |
명시 적 형변환을 사용하여 파생 클래스 참조에 기본 클래스 개체를 할당 할 수 있습니까? (0) | 2020.10.23 |
Oracle SQL에서 특정 문자까지 하위 문자열을 선택하는 방법은 무엇입니까? (0) | 2020.10.23 |
Windows 10에 Windows SDK 7.1을 설치할 수 없습니다. (0) | 2020.10.23 |