【问题标题】:What is the advantage of using the use function in PHP?在 PHP 中使用 use 函数有什么好处?
【发布时间】:2014-03-14 18:28:43
【问题描述】:

如果这样写我的回调函数...

$direction = 'asc';      
$compare = function ($a, $b) use ($direction) {
...

...然后脚本显示与此相同的行为:

$direction = 'asc';      
$compare = function ($a, $b, $direction = 'asc') {
...

在这两种情况下,变量都是按值传递的。 那么,使用 use-function 而不是通过标准 function-parameter 传递变量有什么好处呢?

【问题讨论】:

  • 这是 PHP 表达闭包的方式。 check this answer 并搜索 closure 的含义,如果您不了解此概念。
  • 尝试更改第二个示例中的第一个 $direction 变量,看看它根本不起作用。

标签: php closures


【解决方案1】:
$compare = function ($a, $b, $direction = 'asc') { ... };

这是一个普通函数,接受 3 个参数,最后一个参数是可选的。它需要被称为:

$compare('foo', 'bar', 'desc');

这里:

$direction = 'asc';      
$compare = function ($a, $b, $direction = 'asc') { ... };

这两个$direction 变量完全没有任何关系。

如果你这样做:

usort($array, $compare)

那么usort 只会使用两个 参数调用$compare,它永远不会传递第三个参数,第三个参数将始终保持其默认值asc

$direction = 'asc';      
$compare = function ($a, $b) use ($direction) { ... };

这里$direction变量实际上包含在函数中。

$direction = 'asc';  -----------------+
                                      |
$compare = function ($a, $b) use ($direction) {
                                      |
    echo $direction;  <-------------- +
};

您正在将变量的范围扩展到函数中。这就是use 所做的。另见Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?

【讨论】:

  • 你写的答案非常好/甚至发帖。你考虑过写书吗?我想买一个。
  • @HAL 谢谢。也许有一天当我没有孩子和/或没有全职工作并且有一个话题要写的时候。 ;-P
  • "...我想买一个。"我也是。
【解决方案2】:

什么是use

use 表示从当前作用域继承变量或值。参数可以从任何地方给出,但used 变量只能在某些情况下存在。因此,您可能无法在未设置 used 变量的范围之外使用闭包:

<?php
header('Content-Type: text/plain; charset=utf-8');

$fn = function($x)use($y){
    var_dump($x, $y);
};

$fn(1);
?>

演出:

Notice:  Undefined variable: y in script.php on line 4
int(1)
NULL

但是,您可以使用参数化闭包而无需这种范围依赖性:

<?php
header('Content-Type: text/plain; charset=utf-8');

$fn = function($x, $y = null){
    var_dump($x, $y);
};

$fn(1);
?>

查看相关问题: In PHP 5.3.0, what is the function "use" identifier?

有什么优势?

use 构造的主要用例之一是使用闭包作为其他函数(方法)的回调。在这种情况下,您必须遵循固定数量的函数参数。因此,将额外参数(变量)传递给回调的唯一方法是 use 构造。

<?php
header('Content-Type: text/plain; charset=utf-8');

$notWannaSeeThere = 15;
$array  = [ 1, 15, 5, 45 ];
$filter = function($value) use ($notWannaSeeThere){
    return $value !== $notWannaSeeThere;
};

print_r(array_filter($array, $filter));
?>

演出:

Array
(
    [0] => 1
    [2] => 5
    [3] => 45
)

在这个例子中,array_filter() 使用了$filter 闭包,并且只用一个参数调用 - 数组元素值(我们“不能”强制它使用额外的参数)。不过,我们可以传递其他变量,这些变量在父作用域中可用。

参考:anonymous functions.

从父作用域继承变量与使用不同 全局变量。

【讨论】:

  • "use 构造的主要用例之一是使用闭包作为其他函数(方法)的回调。在这种情况下,您必须遵循固定数量的函数参数。所以传递额外的唯一方法回调的参数(变量)是使用构造。”伟大的!这已经完美地回答了它。如果我使用 PHP usort 函数 (de1.php.net/manual/en/function.usort.php),则需要一个带有 EXACT 2 参数的回调函数。使用 use-keyword 我可以提供声明的回调并传递其他参数。非常感谢。你帮了我很多。
  • @michael.zech 如果对您有帮助,您可以选择答案为“已接受”,以关闭您的问题。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 2019-08-23
  • 2017-06-27
  • 2012-05-22
  • 2011-08-06
  • 1970-01-01
相关资源
最近更新 更多