2008-10-30 110 views
59

有没有办法在PHP的同一个类中动态调用方法?我没有语法正确的,但我希望做一些与此类似:PHP中的动态类方法调用

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

是它原来的问题?我正在寻找动态调用方法,我发现这个问题。它的语法与andy.gurin给出的语法相同,我没有看到显示问题更新的链接。无论如何...感谢有问题和感谢的贡献者:-) – 2009-07-30 01:43:47

+2

@Luc - 这是原来的问题。事实证明,当我问我的时候我的语法正确,但是我的代码有其他问题,所以它不起作用。 – VirtuosiMedia 2009-07-30 08:09:03

回答

121

还有就是要做到这一点不止一种方法:

$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

+0

我想也许我确实拥有正确的语法,所以我的代码有其他问题,因为它的功能不正常。嗯... – VirtuosiMedia 2008-10-30 20:00:52

9

只要省略括号:

$this->$methodName($arg1, $arg2, $arg3); 
+0

谢谢。我曾经想过,但还没有尝试过。 – VirtuosiMedia 2008-10-30 19:51:37

3

您还可以使用call_user_func()call_user_func_array()

3

如果你在PHP的一个类中工作,那么我会建议在PHP5中使用重载的__call函数。你可以找到参考here

基本上__call为动态函数做什么__set和__get为PHP OO中的变量做了什么。

1

在我的情况。

$response = $client->{$this->requestFunc}($this->requestMsg); 

使用PHP SOAP。

+1

我不知道但要小心安全问题 – tom10271 2016-02-02 01:39:15

1

可以在单个变量使用封闭储存方法:

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兼容。另一个例子here

2

这些年后仍然有效!确保您修剪$ methodName,如果它是用户定义的内容。我无法获得$ this - > $ methodName的工作,直到我发现它有一个领先的空间。

5

可以使用重载在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