【问题标题】:Undefined variable inside PHP array_filter [duplicate]PHP array_filter中的未定义变量[重复]
【发布时间】:2015-09-01 04:47:11
【问题描述】:

这可能是一个非常愚蠢的问题,但我就是无法理解 PHP 作用域是如何处理这段代码的:

$leagueKey = 'NFL';
$response['response'] = array_filter($response['response'], function($tier){
    return ($tier['LeagueKey'] === $leagueKey ? true : false);
});

当我运行它时,我得到一个“未定义变量:leagueKey”异常。另一方面,这非常有效:

$response['response'] = array_filter($response['response'], function($tier){
    return ($tier['LeagueKey'] === 'NFL' ? true : false);
});

为什么 PHP 在 array_filter 函数中看不到我的 $leagueKey 变量?

谢谢!

【问题讨论】:

  • 因为$leagueKey 是在该函数之外定义的。为了使用它,您可以在匿名函数中使用global $leagueKey,但这不是最好的方法
  • 因为它超出了范围,就像任何函数一样,您必须将外部参数提供给它。 $leagueKey 在函数之外,字符串'NFL' 在里面,所以它可以工作。
  • 试试这个 $response['response'] = array_filter($response['response'], function($tier) use $leagueKey { return ($tier[' LeagueKey'] === $leagueKey ? true : false); });
  • 不应将其标记为重复...。这是一个很好的问题,与另一个不同。只是一个类似的答案。

标签: php array-filter


【解决方案1】:

您的$leagueKey 变量超出了匿名函数(闭包)的范围。幸运的是,PHP 提供了一种将变量带入作用域的非常简单的方法——use 关键字。试试:

$leagueKey = 'NFL';
$response['response'] = array_filter($response['response'], function($tier) use ($leagueKey) {
    return $tier['LeagueKey'] === $leagueKey;
});

这只是告诉您的匿名函数“使用”当前范围内的 $leagueKey 变量。

编辑

令人兴奋的 PHP 7.4 更新 - 我们现在可以使用“短闭包”来编写没有自己作用域的函数。该示例现在可以这样编写(在 PHP 7.4 中):

$response['response'] = array_filter(
    $response['response'], 
    fn($tier) => $tier['LeagueKey'] === $leagueKey
);

【讨论】:

    【解决方案2】:

    试试这个

    $response['response'] = array_filter($response['response'], function($tier) use ($leagueKey) {
     return ($tier['LeagueKey'] === $leagueKey ? true : false); 
    }); 
    

    【讨论】:

    • 你缺少括号,use ($leagueKey)
    • @Sverri M. Olsen 谢谢,没有括号就不行
    【解决方案3】:

    这就是所有变量的作用域。您的匿名函数对它之外的变量一无所知。这适用于所有类型的函数:如果您需要使用函数外部的变量 - 您将其传递给函数。在这种情况下,你不能传递任何东西,但如果你运行的是 PHP5.3+,你可以做 function($tier) use ($leagueKey){ 这将告诉函数它需要使用在其外部定义的 $leagueKey。如果您的 php 低于 5.3,则必须使用以下解决方法: link

    【讨论】:

      【解决方案4】:

      尝试全局变量:

      $GLOBALS['leagueKey'] = 'NFL';
      $response['response'] = array_filter($response['response'], function($tier){
          return ($tier['LeagueKey'] === $leagueKey ? true : false);
      });
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      相关资源
      最近更新 更多