e1
function test_1() { $a = 'php'; $func = function ($b) use ($a) { // $a = 'java'; echo $b.'_'.$a; }; return $func; } $test = test_1(); $test('hello');
以上效果会输出 hello_php 那末能够看到 $a 被作为了变量 经由过程use通报给了 匿名函数 func 作为参数运用;假如去掉$a = 'java'的解释,那末以上效果会输出 hello_java
e2:将上面的函数改写为
function test_2() { $a = 'php'; $func = function ($b) use ($a) { // $a = 'go'; echo $b.'_'.$a; }; $a = 'java'; return $func; } $test = test_2(); $test('hello');
以上效果会输出 hello_php 申明在test_2中第二次为$a赋值的时刻,并没有通报的到 func函数内里去。
一样的假如去掉 $a = 'go';那末以上效果会输出 hello_go
e3:现在为$a 加上援用
function test_3() { $a = 'php'; $func = function ($b) use (&$a) { //$a = 'go'; echo $b.'_'.$a; }; $a = 'java'; return $func; } $test = test_3(); $test('hello');
以上效果会输出 hello_java 申明在地点援用的时刻 变量 a 的值会通报到 函数func内里去。
一样的假如去掉 $a = 'go';
那末以上效果会输出 hello_go;
以上三个简朴的测试,很邃晓的申明的闭包内里参数的作用域。
在没有运用地点援用的时刻 匿名函数的变量值,不会跟着外部变量的转变而转变。(闭包的意义)
在运用了地点援用以后,参数值会被外部函数的参数值所转变。
更多PHP相干学问,请接见PHP教程!
以上就是PHP 闭包之变量作用域的细致内容,更多请关注ki4网别的相干文章!