购买
下载掌阅APP,畅读海量书库
立即打开
畅读海量书库
扫码下载掌阅APP

4.6 匿名函数

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

匿名函数的示例如下:

    <?php
    echo preg_replace_callback('~-([a-z])~', function ($match) {
       return strtoupper($match[1]);
    }, 'hello-world');
    ?>

此例中,preg_replace_callback()函数接收的第一个参数为正则表达式,第二个参数为回调函数,第三个参数为所要匹配的元素。关于正则表达式的用法详见第10章,这里只举个例子说明匿名函数的使用场景。

闭包函数也可以作为变量的值来使用,PHP会自动把此种表达式转换成内置类closure的对象实例。把一个closure对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号“:”。示例如下:

    <?php
    $greet = function($name)
    {
               echo "hello $name \n";
    };
    $greet('World');
    $greet('PHP');
    ?>

以上程序的执行结果为:hello World hello PHP 。

闭包可以从父作用域中继承变量,这时需要使用关键词use,示例如下:

    <?php
    $message = 'hello';
// 没有 "use" $example = function () { var_dump($message); }; echo $example(); //输出值为 null
// 继承 $message $example = function () use ($message) { var_dump($message); }; echo $example(); //输出结果hello
// 当函数被定义的时候就继承了作用域中变量的值,而不是在调用时才继承 // 此时改变 $message 的值对继承没有影响 $message = 'world'; echo $example(); // 输出结果hello
// 重置 $message 的值为"hello" $message = 'hello';
// 继承引用 $example = function () use (&$message) { var_dump($message); }; echo $example(); //输出结果 hello
// 父作用域中 $message 的值被改变,当函数被调用时$message的值发生改变 // 注意与非继承引用的区别 $message = 'world'; echo $example(); // 输出结果 world
// 闭包也可接收参数 $example = function ($arg) use ($message) { var_dump($arg . ' ' . $message); }; $example("hello"); // 输出结果 hello world ?>

以上程序的执行结果为: fej46b339e4DDJgjF9uR+1qppWY97WAMmg+0a8Eu2C7rttCw2dnwNDA5mPTqUyDz

      NULL string(5) "hello" string(5) "hello" string(5) "hello" string(5) "world"
  string(11) "hello world”
点击中间区域
呼出菜单
上一章
目录
下一章
×