来自匿名函数的PHP访问变量

时间:2012-12-23 16:20:04

标签: php function scope

  

可能重复:
  Render a variable during creation of anonymous PHP function

我对PHP仍然很陌生,这让我感到困扰:

class Controller {
    ...
    ...
    function _activateCar() {
        $car_id = $this->data['car']->getId();
        // $car_id == 1
        $active_car = array_filter($this->data['cars'], function($car){
            // $car_id undefined
            return $car->getId() == $car_id;
        });
    }
    ...
    ...
}

为什么array_filter中的函数不能访问$car_id变量?继续说未定义。

还有另一种方法可以$car_id访问$_GET['car_id'] = $car_id;吗?使用global关键字无效。

2 个答案:

答案 0 :(得分:5)

您需要将use($car_id)添加到您的匿名函数中,如下所示:

$active_car = array_filter($this->data['cars'], function($car) use($car_id){
    // $car_id undefined
    return $car->getId() == $car_id;
});

答案 1 :(得分:5)

匿名函数可以使用use关键字导入选择变量:

$active_car = array_fiter($this->data['cars'],function($car) use ($car_id) {
    return $car->getId() == $car_id;
});