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));
リフレクションAPIhttp : //php.net/manual/en/class.reflection.phpを使用することもできます
call_user_func_arrayはあなたのためのものです。
call_user_func_array($this->$name, ...)、なぜそれが機能しないのか疑問に思いました!
中括弧は省略してください。
$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
これらすべての年後もまだ有効です!ユーザー定義のコンテンツである場合は、必ず$ 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"
編集:コードを編集しましたが、PHP5.3と互換性があります。ここに別の例