php中匿名函數的使用

1、作爲回調函數使用

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

2、作爲變量賦值

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');

結果:
這裏寫圖片描述
3、 從父作用域繼承變量

<?php
$message = 'hello';

// 沒有 "use"
$example = function () {
    var_dump($message);
};
echo $example();

// 繼承 $message
$example = function () use ($message) {
    var_dump($message);
};
echo $example();

結果:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章