【问题标题】:How to access a variable inside a function declared as a variable? [duplicate]如何访问声明为变量的函数内的变量? [复制]
【发布时间】:2012-01-22 10:11:13
【问题描述】:

可能重复:
Is it possible to access outer local variable in PHP?
PHP closure scope problem

给定这个 PHP 函数:

function get_deals_by_type($records, $type) {
  $available = function($record) {
    if($record->mobile_type == $type) return $record;
  };
  return array_filter($records, $available);
}

...如何访问在$available 中声明的函数内部传入的$type?就目前而言,$typearray_filter 返回NULL,无论传递给get_deals_by_type() 的值是什么。

【问题讨论】:

    标签: php scope


    【解决方案1】:

    不确定,但是:

    function get_deals_by_type($records, $type) {
      $available = function($record) use ($type) {
        if($record->mobile_type == $type) return $record;
      };
      return array_filter($records, $available);
    }
    

    http://www.php.net/manual/de/functions.anonymous.php(购物车示例)

    【讨论】:

    • 是的!正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多