2012-12-23 155 views
-1

可能重複:
Render a variable during creation of anonymous PHP functionPHP訪問變量

我還與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關鍵字沒有幫助。

回答

5

您需要添加use($car_id)到您的匿名函數,像這樣:

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

匿名函數可以導入選擇的變量與use關鍵字:

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