来自匿名函数的PHP访问变量[重复]

Possible Duplicate:
Render a variable during creation of anonymous PHP function

I am still quite new with PHP and this bothers me:

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;
        });
    }
    ...
    ...
}

Why can't the function inside array_filter access the $car_id variable? Keeps saying undefined.

Is there an other way to make $car_id accessible than to make a $_GET['car_id'] = $car_id;? Using the global keyword didn't help.

You need to add use($car_id) to your anonymous function, like so:

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

Anonymous functions can import select variables with the use keyword:

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