Dynamic class method invocation in PHP

后端 未结 8 1934
感动是毒
感动是毒 2020-11-28 05:05

Is there a way to dynamically invoke a method in the same class for PHP? I don\'t have the syntax right, but I\'m looking to do something similar to this:

$t         


        
相关标签:
8条回答
  • 2020-11-28 05:32

    You can use the Overloading in PHP: Overloading

    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
    
    0 讨论(0)
  • 2020-11-28 05:39

    Just omit the braces:

    $this->$methodName($arg1, $arg2, $arg3);
    
    0 讨论(0)
提交回复
热议问题