PHP匿名函数

栏目: PHP · 发布时间: 7年前

内容简介:PHP菜鸟匿名函数(Anonymous functions),也叫闭包函数(closures),允许临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。举例:

PHP菜鸟

匿名函数(Anonymous functions),也叫闭包函数(closures),允许临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。

举例:

<?php
    $greet=function($name){
        echo 'Hello '.$name;
    };
    $greet('World!');
?>

这样会输出

Hello World!

假设现在要在匿名函数中调用普通的变量:

<?php
    $name='Hello World!';
    $greet=function(){
        echo $name;
    };
    $greet();
?>

如果是这么使用,那么就会报一个错误:

PHP Notice:  Undefined variable: name in /code/main.php on line 4

应该是这么使用:

<?php
    $name='Hello World!';
    $greet=function() use ($name){
        echo $name;
    };
    $greet();
?>

这样就会返回

Hello World!

以上理解如果有不对的地方,还望dalao们指正。


以上所述就是小编给大家介绍的《PHP匿名函数》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Software Engineering for Internet Applications

Software Engineering for Internet Applications

Eve Andersson、Philip Greenspun、Andrew Grumet / The MIT Press / 2006-03-06 / USD 35.00

After completing this self-contained course on server-based Internet applications software, students who start with only the knowledge of how to write and debug a computer program will have learned ho......一起来看看 《Software Engineering for Internet Applications》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具