Blogger Information
Blog 23
fans 0
comment 0
visits 13490
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
20190929 作业
王长中的博客
Original
628 people have browsed it

匿名函数的应用场景:

       1.因为匿名函数没有函数名,所以在引用的时候,就要把它作为值赋给一个变量,匿名函数也可以和普通函数一样声明参数:

实例

<?php
$a = function ($a, $b) {
    return $a * $b;
};
echo $a(15, 20);
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

     2.回调引用:在函数中定义一个匿名函数,并且调用

实例

<?php
function fun()
{
    $fun = function ($a) {
        echo $a;
    };
    $fun('wcz');
}

echo fun();
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

3.闭包

实例

<?php
function funcstr(){
    $str='wcz123';
    $s=function() use ($str){
       return $str;
    };
    return  $s;
}
echo $f=funcstr()();
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

总结:

        匿名函数是临时创建一个没有命名的函数,当把匿名函数作为值赋给变量时,花括号后面要加上分号,从父作用域继承变量时,用关键字USE,从父作用域的变量与全局变量不一样,用到全局变量时要用global 变量名,或是$GLOBAL[变量名]声明。




Correction status:qualified

Teacher's comments:总结的不错, 在项目要灵活应用
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!