2016-09-30 52 views
5

我現在有一個依賴注入模塊,讓我來創建對象的工廠內一個全局對象:如何接入的方法封閉

class DiModule 
{ 
    private $Callbacks; 

    public function set(
     $foo, 
     $bar 
    ) { 
     $this->Callbacks[$foo] = $bar; 
    } 

    public function get(
     $foo 
    ) { 
     return $this->Callbacks[$foo]; 
    } 
} 

然後我有一個事件對象存儲的方法關閉和會觸發事件。

class Event 
{ 
    private $Sesh; 
    private $Method; 

    public function set(
     $sesh = array(), 
     $method 
    ) { 
     $this->Sesh = $sesh; 
     $this->Method = $method; 
    } 

    public function get(
    ) { 
     return [$this->Sesh,$this->Method]; 
    } 
} 

然後我有一個偵聽器對象,它搜索會話集並觸發與該對象關聯的事件。

class Listener 
{ 
    private $Sesh; 
    public function setSesh(
     $foo 
    ) { 
     $this->Sesh = $foo; 
    } 

    private $Event; 
    public function set(
     $foo, 
     Event $event 
    ) { 
     $this->Event[$foo] = $event; 
    } 

    public function dispatch(
     $foo 
    ) { 
     $state = true; 

     if(isset($this->Event[$foo])) 
     { 
      foreach($this->Event[$foo]->get()[0] as $sesh) 
      { 
       if(!isset($this->Sesh[$sesh]) || empty($this->Sesh[$sesh])) 
       { 
        $state = false; 
       } 
      } 
     } 

     return ($state) ? [true, $this->Event[$foo]->get()[1]()] : [false, "Event was not triggered."]; 
    } 
} 

這是正在執行

$di = new DiModule(); 

$di->set('L', new Listener()); 
$di->set('E', new Event()); 

$di->get('E')->set(['misc'], function() { global $di; return $di; }); 

$di->get('L')->setSesh(array('misc' => 'active')); // not actual sessions yet 
$di->get('L')->set('example', $di->get('E')); 
var_dump($di->get('L')->dispatch('example')); 

這樣的一個例子的問題是,當我嘗試訪問我的全球$di封閉裏面,我用Google搜索這個無數次,但無法找到一個解決方案。

+1

在你的示例代碼中可能只是一個錯誤,但對我來說,它看起來像你的'DiModule''''和'get'方法混淆了。 'set'返回對象,'get'設置它。 – Andy

回答

4

您需要使用use關鍵字才能從閉包中訪問外部變量。

所以這個:

$di->get('E')->set(['misc'], function() { global $di; return $di; }); 

應該這樣寫:

$di->get('E')->set(['misc'], function() use ($di) { return $di; }); 
+0

輝煌,這工作!我會看看使用這個關鍵字 - 我以前從來沒有見過這種情況 – KDOT

2

DiModule類的set()get()方法似乎有不匹配的名稱/實現。

您發佈的代碼有以下方法:

function get($foo, $bar) { /* ... */ } 
function set($foo) { /* ... */ } 

應該最有可能的是:

function get($foo) { /* ... */ } 
function set($foo, $bar) { /* ... */ } 

爲了使這些錯誤的可能性較小,給你的論點有意義的名稱(如$key$value)而不是通用的$foo$bar。那麼它會更容易被發現。