array_walk_recursive,在PHP中使用外部变量的函数

时间:2012-09-02 18:52:14

标签: php

   $total_materials_cost = 0;
   array_walk_recursive($materials, function($item, $key) {
        if (in_array($key, array('id'))) {

                    (....)

                    $total = $material_price * $material['amount'];

                    $total_materials_cost += $total;
                }
            }
        }
    });
echo $total_materials_cost;

对于上面的代码,我在第$total_materials_cost += $total;行得到错误,说变量未定义 - 我相信这是因为我在函数内部?但是我怎么能以任何方式绕过/为此做一个变通方法,所以它确实添加了变量?

1 个答案:

答案 0 :(得分:14)

使用use关键字:

$total_materials_cost = 0;
array_walk_recursive($materials, function($item, $key) use(&$total_materials_cost) {
  if (in_array($key, array('id'))) {
    // (....)
    $total = $material_price * $material['amount'];
    $total_materials_cost += $total;
  }
});
echo $total_materials_cost;

传递引用(&)以更改闭包之外的变量。

相关问题