如何在声明为变量的函数内访问变量?

时间:2011-12-17 00:23:42

标签: php scope

  

可能重复:
  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);
}

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

1 个答案:

答案 0 :(得分:4)

不确定但是:

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(购物车示例)