1. 程式人生 > >laravel匿名函式

laravel匿名函式

匿名函式(Anonymous functions),也叫閉包函式(closures),允許 臨時建立一個沒有指定名稱的函式。最經常用作回撥函式(callback)引數的值。具體介紹請查官方手冊
http://php.net/manual/zh/class.closure.php

匿名函式示例

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

匿名函式可以賦值個一個變數

PHP 會自動把此種表示式轉換成內建類 Closure 的物件例項。把一個 closure 物件賦值給一個變數的方式與普通變數賦值的語法是一樣的,最後也要加上分號

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

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

匿名函式從父作用域繼承變數。 任何此類變數都應該用 use 語言結構傳遞進去

<?php
$message = 'hello';

// 沒有 "use"
$example = function () {
    var_dump($message);
    echo "<br/>";
};
echo $example();//輸出 null

// 繼承 $message
$example = function () use ($message) {
    var_dump($message);
    echo "<br/>";
};
echo $example();//hello

// Inherited variable's value is from when the function
// is defined, not when called
$message = 'world';
echo $example();//輸出 hello

// Reset message
$message = 'hello';

// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
    echo "<br/>";
};
echo $example();//輸出 hello

// The changed value in the parent scope
// is reflected inside the function call
$message = 'world';
echo $example();//輸出 world

// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    var_dump($arg . ' ' . $message);
    echo "<br/>";
};
$example("hello");//輸出 hello world
?>

在laravel框架中使用了大量的匿名函式,舉例一個檔案

檔案:laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php
這是一個容器檔案

<?php
    //省略程式碼
    public function bind($abstract, $concrete = null, $shared = false)
    {
        //省略程式碼
        //判斷是否有這個閉包函式(匿名函式),存在返回false,存在返回true
        if (! $concrete instanceof Closure) {
            //引數不是閉包函式,預設生成一個閉包函式
            $concrete = $this->getClosure($abstract, $concrete);
        }
        //省略程式碼

    }
    protected function getClosure($abstract, $concrete)
    {
        return function ($c, $parameters = []) use ($abstract, $concrete) {
            $method = ($abstract == $concrete) ? 'build' : 'make';

            return $c->$method($concrete, $parameters);
        };
    }
    //省略程式碼

QQ交流群:136351212
檢視原文: