2016-09-24 116 views
-1

我想在運行時創建方法並將它們添加到類中。好的,讓我解釋一下它的背景。我有一個字符串數組。例如,基於這個數組,我想創建具有不同功能的方法,具體取決於該字符串。在類中創建動態方法

$fruits = ["apple", "pear", "avocado"]; 
foreach($fruits as $fruit){ 
    if($fruit == "apple"){ 
    // create function doing X 
    }else{ 
     // create function doing Y 
    } 
} 

PHP有方法create_function()但它創建了一個annonymous功能,我不感興趣的。我想能夠調用像MyClass->apple()

這可能嗎?

回答

1

PHP沒有這樣的函數create_method(),你可能會想到create_function()。然而,PHP類確實有一個神奇的方法,它允許您在對象上使用不可訪問的方法調用函數調用__call(),對於靜態類方法也有__callStatic()

__call()在調用對象上下文中的不可訪問方法時被觸發。

__callStatic()在調用靜態上下文中不可訪問的方法時被觸發。

但是區分在運行時動態添加方法的概念與在運行時動態創建代碼的想法是很重要的。例如,註冊回調的概念通常是使用閉包的完善的概念。

class Fruits { 

    protected $methods = []; 

    public function __call($name, $arguments) { 
     if (isset($this->methods[$name])) { 
      $closure = $this->methods[$name]; 
      return $closure(...$arguments); 
     } 
    } 

    public function registerMethod($name, Callable $method) { 
     $this->methods[$name] = $method; 
    } 

} 

$apple = function($color) { 
    return "The apple is $color."; 
}; 

$pear = function($color) { 
    return "The pear is $color."; 
}; 

$avocado = function($color) { 
    return "The avocado is $color."; 
}; 

$methods = ["apple" => $apple, "pear" => $pear, "avocado" => $avocado]; 

$fruits = new Fruits; 

foreach($methods as $methodName => $method) { 
    $fruits->registerMethod($methodName, $method); 
} 

echo $fruits->apple("red"), "\n"; 
echo $fruits->pear("green"), "\n"; 
echo $fruits->avocado("green"), "\n"; 

輸出

 
The apple is red. 
The pear is green. 
The avocado is green. 
+0

我不好,我想念鍵入create_method。對不起 –

+0

使用這種方法,函數的定義必須使用kwown數組的大小和值來完成嗎? –

+0

不,PHP數組的大小是動態的。 – Sherif