1、use最常用在给类取别名,还可以用在闭包函数中,代码如下

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

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

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

示例一

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

示例二

<?phpfunction index() {$a = 1;return function () use(&$a){echo $a;$a++;};}$a = index();$a();$a();$a();$a();$a();$a();//123456?>

以上就是use关键字在php中的使用,更多请关注亿速云其它相关文章!