代码之家  ›  专栏  ›  技术社区  ›  cluster1

在PHP中使用use函数有什么好处?

  •  2
  • cluster1  · 技术社区  · 12 年前

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

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

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

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

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

    2 回复  |  直到 7 年前
        1
  •  1
  •   Community Mohan Dere    9 年前
    $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 = '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? .

        2
  •  0
  •   Community Mohan Dere    9 年前

    是什么 use ?

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

    <?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? .

    什么是优势?

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

    <?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
    )
    

    在该示例中, $filter 闭包由使用 array_filter() 并且只使用一个参数-数组元素值(并且我们 “不能” 强制它使用其他参数)。尽管如此,我们仍然可以传递在父范围中可用的附加变量。

    参考: anonymous functions .

    从父范围继承变量与使用 全局变量。

    推荐文章