Use of use keyword in php
1. use is most commonly used to retrieve classes Aliases can also be used in closure functions. The code is as follows
<?php function test() { $a = 'hello'; return function ($a)use($a) { echo $a . $a; }; } $b = test(); $b('world');//结果是hellohello
When running the test function, the test function returns the closure function. The variable in use in the closure function is $ in the test function. a variable, when the closure function is run, "hellohello" is output, which means that the priority of the variables in the function body is: the priority of the variables in use is higher than the priority of the closure function parameters.
2. The parameters in use can also be passed by reference. The code is as follows
Example 1
<?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
Example 2
<?php function index() { $a = 1; return function () use(&$a){ echo $a; $a++; }; } $a = index(); $a(); $a(); $a(); $a(); $a(); $a(); //123456 ?>
Thank you all for watching, I hope you can improve after learning how to use the use keyword.
Recommended tutorial: "PHP Tutorial"
The above is the detailed content of The use of use keyword in php (including code). For more information, please follow other related articles on the PHP Chinese website!