【问题标题】:PHP access variable from anonymous function [duplicate]来自匿名函数的PHP访问变量[重复]
【发布时间】:2012-12-23 16:20:03
【问题描述】:

可能重复:
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变量?一直说未定义。

除了创建$_GET['car_id'] = $car_id; 之外,还有其他方法可以使$car_id 可访问吗?使用 global 关键字没有帮助。

【问题讨论】:

    标签: php function scope


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-19
        • 2014-04-09
        • 1970-01-01
        • 2013-02-09
        • 1970-01-01
        • 2012-07-10
        • 1970-01-01
        相关资源
        最近更新 更多