【发布时间】: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