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