【问题标题】:How is use statement used as function argument in php [duplicate]php中如何将use语句用作函数参数[重复]
【发布时间】:2018-02-15 08:11:52
【问题描述】:

来自documentation,简单来说我推断array_reduce将一个数组作为第一个参数,根据第二个参数中定义的函数进行处理,并迭代结果,直到第一个参数数组的所有值都用完.

但特别是在本例中,它采用从getActiveWidgets() 返回的数组。到这里好了,什么是use语句?

$widgets = array_reduce(
            ThemeActiveWidgets::getActiveWidgets(),
            function ($carry, $item) use($model) {
                if ($item['part_id'] === $model['id']) {
                    $carry[]=$item;
                }
                return $carry;
            },
            []
        );

【问题讨论】:

  • 使用声明...?
  • use 只是使$model 在函数体内可用。否则您将无法访问它。
  • use 语句接受一个变量并将其注入函数的作用域。
  • php.net/manual/en/functions.anonymous.php : Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.
  • ok@aynber, 和将array_reduce包装在另一个函数中并提供$model作为参数一样吗?

标签: php


【解决方案1】:

我会为你分解一下。

函数array_reduce() 接受两个参数,第一个是数组,第二个是函数,在本例中是闭包或anonymous 函数。

在您的代码中,您通过调用ThemeActiveWidgets::getActiveWidgets() 并将其作为第一个参数传递给array_reduce() 来获取一个数组。作为第二个参数,您传递一个函数,如下所示:

function ($carry, $item) use($model) { ... }

由于这是一个匿名函数,变量$model(无论您在哪里定义)不在此匿名函数的范围内,简而言之,这意味着您无法在匿名函数中访问该$model 变量.但是,如果您通过在函数声明中使用 use($model) 将其“传递”到函数的作用域中,则可以访问它。

关于 if 语句 if ($item['part_id'] === $model['id']),您只是在访问匿名函数的第二个参数,并将索引 ['part_id'] 保存的值与 $model['id'](也是一个数组)保存的值进行比较.

我希望这个解释有帮助!

【讨论】:

  • 和将array_reduce包装在另一个函数中并提供$model作为参数一样吗?
猜你喜欢
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多