use关键字在php里的使用含代码
发布时间:2022-06-24 13:23:11 所属栏目:PHP教程 来源:互联网
导读:use关键字在php中的使用 1、use最常用在给类取别名,还可以用在闭包函数中,代码如下: ?php function test() { $a = hello; return function ($a)use($a) { echo $a . $a; }; } $b = test(); $b(world);//结果是hellohello 当运行test函数,test函数返回
use关键字在php中的使用 1、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中的变量的优先级比闭包函数参数中的优先级要高。 2、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 ?>。 (编辑:昌吉站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐