2013-12-20 47 views
0

的引用傳遞數組數據我有一個Eventbus,需要一個濾波器名稱作爲其第一參數和作爲封閉第二參數。就像這樣:如何更改封閉

$this->EventBus->subscribe('FilterTestEvent', function(){/*Do Something*/}); 

它被稱爲是這樣的:

$filteredValue = $this->EventBus->filter('FilterTestEvent', $anyValue); 

我現在想要的是傳遞一個數組引用到再以任何方式改變了閉幕(這裏:添加元素)和然後返回的東西作爲濾波值:

$item_to_change = array('e1' => 'v1', 'e2' => 'v2'); 

$this->EventBus->subscribe('FilterTestEvent', function(&$item){ 
    $item['new'] = 'LoremIpsum'; 

    return true; 
}); 

$filtered = $this->EventBus->filter('FilterTestEvent', $item_to_change); 

現在我想一個print_r($item_to_change)想到如下所示:

Array 
(
    [e1] => v1 
    [e2] => v2 
    [new] => LoremIpsum 
) 

但是,相反它看起來像原來的數組:

Array 
(
    [e1] => v1 
    [e2] => v2 
) 

的eventbus內部存儲所有的封鎖,如果需要通過call_user_func_array()與封閉的第一個參數和值作爲唯一的參數數組元素調用它們。

我如何能實現它的意思嗎?

源代碼以Eventbus:http://goo.gl/LAAO7B

回答

0

確定。我找到了答案。過濾器函數需要改變,以便它接受數組作爲值,我可以在其中保存引用。有關詳情請參閱差異修訂1和Eventbus源代碼版本2,在這裏:goo.gl/GBocgl

0

也許這行:

$filtered = $this->EventBus->filter('FilterTestEvent', $item_to_change); 

應該return一個新的過濾陣列,不修改原始一個。

所以檢查:

print_r($filtered); 

按引用傳遞,可以通過修改功能(增加&):

function filter(&$array){ //Note & mark 
    $array['new_index'] = "Something new" ; 
} 

$array = array("a"=> "a"); 
filter($array); //The function now receives the array by reference, not by value. 
var_dump($array); //The array should be modified. 

編輯:


讓您的回調返回已過濾的數組:

$this->EventBus->subscribe('FilterTestEvent', function(&$item){ 
    $item['new'] = 'LoremIpsum'; 

    return $item ; 
}); 

按引用傳遞不應該在這裏工作,因爲在源代碼$value變量被交換與另一個值後返回。

+0

實際上是$過濾的價值現在應該,因爲這是過濾器返回設置爲true。 是的,你說得對。但封閉已經做到了。 – fsebwas

+0

嗯,讓我看看文檔。 – vikingmaster

+0

你的意思是什麼文件? Eventbus源代碼? - 上面包含一個鏈接。 – fsebwas