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

PHP匿名函数和JS匿名函数

WBOY
Release: 2016-06-20 12:30:17
Original
837 people have browsed it

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>
Copy after login

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

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template