可能重复:
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
关键字无效。
答案 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;
});