Home  >  Article  >  Backend Development  >  PHP匿名函数和JS匿名函数

PHP匿名函数和JS匿名函数

WBOY
WBOYOriginal
2016-06-20 12:30:17812browse

php5.5新添加一个新特性 yeild 官方文档,想用闭包模拟一下yeild,然后发现JS和PHP闭包的差别

<?php function php_shell(){    $arr = [9,8,7,6,5,4,3,2,1];    $func = function () use($arr){  //use(&$arr) 结果会不一样        return array_pop($arr);    };    return $func; } $func = php_shell(); for($i = 0 ; $i <= 6; $i++){    echo $func();    echo "<br/>/r/n"; } ?> <script>     function js_shell(){        var arr = [9,8,7,6,5,4,3,2,1];        var func = function(){            return arr.pop();        };        return func;     }     var func = js_shell();     for(var i = 0 ; i <= 6; i++){        console.log(func());     } </script>

结果截图(左边是PHP结果,右边是JS结果)两边

很明显:JS和PHP在闭包的变量的处理有差异再PHP匿名函数 use 变量加上引用符号,然后结果就是一样的了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn