我第一次尝试使用PHP闭包。
我写了一个小函数,它将接受一个数组和它的参数中的一个函数。它的工作是循环遍历给定的数组,并在每个元素上执行$函数。
这是我的功能
/**
* It check each item in a giving array for a property called 'controllers',
* when exists it executes the $handler method on it
*
* @param array $items
* @param function $handler
*/
protected function addSubControls($items, $handler)
{
foreach( $items as $item){
if( property_exists($item, 'controllers')){
//At this point we know this item has a sub controller listed under it, add it to the list
foreach($item->controllers as $subControl){
$handler( $subControl );
}
}
}
}
现在我想用两种方式使用这个函数。
第一:对给定数组中的每个项执行方法generateHtmlValues()
。这没有任何问题。
$this->addSubControls($control->items, function($subControl){
$this->generateHtmlValues( $subControl );
});
第二:我想将每个符合条件的项添加到该闭包方法之外使用的数组中。
$controls = ['a','b','c'];
$this->addSubControls($control->items, function($subControl) use(&$controls) {
$controls[] = $subControl->id;
});
var_dump($controls);
在这一点上,我希望$controls
数组的值比原始数组的值多1。但它并没有做到这一点。
我在这里错过了什么?闭包如何填充我通过引用传递的数组?
毕竟,我的代码工作正常。
我看错了输出。
我会保留这个问题,希望它能帮助其他人。