2008-10-30 80 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