PHP 中的动态类方法调用

php
2022-08-30 07:27:45

有没有办法为PHP动态调用同一类中的方法?我没有正确的语法,但我希望做类似这样的事情:

$this->{$methodName}($arg1, $arg2, $arg3);

答案 1

有多种方法可以做到这一点:

$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


答案 2

您可以使用 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

推荐