php 中use关键字的用法【转】

use最常用在给类取别名

use还可以用在闭包函数中,代码如下

<?php
function test() {
    $a = 'hello';
    return function ($a)use($a) {
        echo $a . $a;
    };
}
$b = test();
$b('world');//结果是hellohello

当运行test函数,test函数返回闭包函数,闭包函数中的use中的变量为test函数中的$a变量,当运行闭包函数后,输出“hellohello”,由此说明函数体中的变量的优先级是:use中的变量的优先级比闭包函数参数中的优先级要高

use中的参数也可以使用引用传递的,代码如下

<?php
function test() {
    $a=18;
    $b="Ly";
    $fun = function($num, $name) use(&$a, &$b) {
        $a = $num;
        $b = $name;
    };
    echo "$b:$a<br/>";
    $fun(30,'wq');
    echo "$b:$a<br/>";
}
test();
//结果是Ly:18
//结果是wq:30
<?php 
function index() {
        $a = 1;
        
        return function () use(&$a){
                echo $a;
                $a++;
        }; 
}
 
$a = index();
 
 
$a();
$a();
$a();
$a();
$a();
$a();
//123456
 ?>

来源:https://blog.csdn.net/aarontong00/article/details/53792601