mre*_*req -1 php scope function
可能重复:
在创建匿名PHP函数期间呈现变量
我对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;
});
}
...
...
}
Run Code Online (Sandbox Code Playgroud)
为什么array_filter里面的函数不能访问$car_id变量?继续说未定义.
有没有其他方法可以$car_id访问而不是制作$_GET['car_id'] = $car_id;?使用global关键字没有帮助.
您需要添加use($car_id)到您的匿名函数,如下所示:
$active_car = array_filter($this->data['cars'], function($car) use($car_id){
// $car_id undefined
return $car->getId() == $car_id;
});
Run Code Online (Sandbox Code Playgroud)
匿名函数可以使用use关键字导入选择变量:
$active_car = array_fiter($this->data['cars'],function($car) use ($car_id) {
return $car->getId() == $car_id;
});
Run Code Online (Sandbox Code Playgroud)