首頁  >  文章  >  後端開發  >  什麼是匿名函數

什麼是匿名函數

藏色散人
藏色散人原創
2019-01-22 09:23:2814051瀏覽

匿名函數 

匿名函數(Anonymous functions),也稱為閉包函數(closures),允許 暫時建立一個沒有指定名稱的函數。最常用作回呼函數(callback)參數的值。當然,也有其它所應用的情況。

什麼是匿名函數

匿名函數目前是透過 Closure 類別來實現的。

匿名函數範例

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

閉包函數也可以當作變數的值來使用。 PHP 會自動把此種表達式轉換成內建類別 Closure 的物件實例。把一個closure 物件賦值給一個變數的方式與普通變數賦值的語法是一樣的,最後也要加上分號:

 匿名函數變數賦值範例

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

$greet(&#39;World&#39;);
$greet(&#39;PHP&#39;);
?>

閉包可以從父作用域繼承變數。任何此類變數都應該用 use 語言結構傳遞進去。 PHP 7.1 起,無法傳入此類變數: superglobals、 $this 或和參數重名。

從父作用域繼承變數

<?php
$message = &#39;hello&#39;;

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

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

// Inherited variable&#39;s value is from when the function
// is defined, not when called
$message = &#39;world&#39;;
echo $example();

// Reset message
$message = &#39;hello&#39;;

// Inherit by-reference
$example = function () use (&$message) {
    var_dump($message);
};
echo $example();

// The changed value in the parent scope
// is reflected inside the function call
$message = &#39;world&#39;;
echo $example();

// Closures can also accept regular arguments
$example = function ($arg) use ($message) {
    var_dump($arg . &#39; &#39; . $message);
};
$example("hello");
?>

以上例程的輸出類似於:

Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"

這些變數都必須在函數或類別的頭部聲明。從父作用域繼承變數與使用全域變數是不同的。全域變數存在於一個全域的範圍,無論目前在執行的是哪個函數。而 閉包的父作用域是定義該閉包的函數(不一定是呼叫它的函數)。

Closures 與作用域範例:

<?php
// 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
// 其中有一个方法用来计算购物车中所有商品的总价格,该方法使
// 用了一个 closure 作为回调函数。
class Cart
{
    const PRICE_BUTTER  = 1.00;
    const PRICE_MILK    = 3.00;
    const PRICE_EGGS    = 6.95;

    protected   $products = array();
    
    public function add($product, $quantity)
    {
        $this->products[$product] = $quantity;
    }
    
    public function getQuantity($product)
    {
        return isset($this->products[$product]) ? $this->products[$product] :
               FALSE;
    }
    
    public function getTotal($tax)
    {
        $total = 0.00;
        
        $callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };
        
        array_walk($this->products, $callback);
        return round($total, 2);;
    }
}

$my_cart = new Cart;

// 往购物车里添加条目
$my_cart->add(&#39;butter&#39;, 1);
$my_cart->add(&#39;milk&#39;, 3);
$my_cart->add(&#39;eggs&#39;, 6);

// 打出出总价格,其中有 5% 的销售税.
print $my_cart->getTotal(0.05) . "\n";
// 最后结果是 54.29
?>

這篇文章就是匿名函數的介紹,希望對需要的朋友有幫助!

以上是什麼是匿名函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn