【问题标题】:How to execute a closure function and populate an array passed by reference in PHP如何在 PHP 中执行闭包函数并填充通过引用传递的数组
【发布时间】:2016-02-23 08:12:00
【问题描述】:

我是第一次尝试使用 PHP 闭包。

我写了一个小函数,它接受一个数组和一个函数作为参数。它的工作是遍历给定数组并在每个元素上执行 $function。

这是我的功能

/**
 * 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 个。但它没有这样做。

我在这里缺少什么?闭包如何填充我通过引用传递的数组?

【问题讨论】:

  • 附带说明,您可能对array_map() php.net/manual/en/function.array-map.php 感兴趣
  • @Calimero 谢谢你的留言。这听起来与我正在尝试做的非常相似。所以对于我的 senario 1,我将如何使用 array_map? array_map($this->generateHtmlValues, $control->items);?
  • 您是否尝试过在addSubControls() 或闭包中调用echo()error_log(),以确保按预期调用?
  • @Mike A首先注意回调语法(一个参数——当前数组项,返回修改后的项),第一个参数是array_map(),第二个是你要循环的数组超过(或更多,如果需要)。

标签: php closures


【解决方案1】:

毕竟,我的代码可以正常工作。

我看错了输出。

我会保留这个问题,希望对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 2012-05-16
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2011-05-24
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多