2013-08-03 40 views
1

我想將匿名函數存儲在類中的數組中。以下是我的工作代碼。但我不明白爲什麼我必須在第二個參數中傳遞值,而如果沒有從外部設置任何東西,我已經聲明它是一個空數組。php oop:在類中的數組中創建匿名函數

- public function methods($method = "init",$options = array()){ -

任何想法?

class myclass { 

    public function __construct() {} 

    public function methods($method = "init",$options = array()){ 

     $methods = array(
      "init" => function($options){ 
       return $options; 
      }, 

      "run" => function($options){ 
       return $options; 
      }, 
     ); 

     return call_user_func_array($methods[$method], $options); 
    } 
} 

$obj = new myclass(); 
var_dump($obj->methods("init",array("hello world!"))); // string 'hello world!' (length=12) --> correct. 
var_dump($obj->methods("init",array())); // Warning: Missing argument 1 for myclass::{closure}() in...refer to -> "init" => function($options){ 
var_dump($obj->methods("init")); // Warning: Missing argument 1 for myclass::{closure}() in...refer to -> "init" => function($options){ 

我認爲它應該返回這些作爲結果,

var_dump($obj->methods("init",array())); // array (size=0) empty 
var_dump($obj->methods("init")); // array (size=0) empty 

回答

4

您的情況下,正確的關閉聲明:

$methods = array(
    "init" => function() use ($options){ 
     return $options; 
    }, 

    "run" => function() use ($options){ 
     return $options; 
    }, 
); 

如果您包括您的閉合聲明$options變量,其範圍將是封閉本身。因此,將會有一個新的$options變量創建並覆蓋外部函數中的$options變量。

通過使用use關鍵字,您告訴PHP您想要使用傳遞的$options變量(當前已啓動)。現在

,你可以在call_user_func_array呼叫省略第二個參數如下

call_user_func_array($methods[$method]) 
+2

然後換call_user_func – Orangepill

+0

感謝您的回答。它現在完美運行! – laukok

+0

@Orangepill感謝您的評論:) –