php匿名函數(也叫閉包函數)

匿名函數(Anonymous functions),也叫閉包函數(closures),容許 臨時建立一個沒有指定名稱的函數。
最常常用做回調函數(callback)參數的值 。固然,也有其它應用的狀況。 

Example #1 匿名函數示例

也就是之前傳函數名,如今能夠直接傳匿名函數做爲參數了php

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


閉包函數也能夠做爲變量的值來使用。PHP 會自動把此種表達式轉換成內置類 Closure 的對象實例
把一個 closure 對象賦值給一個變量的方式與普通變量賦值的語法是同樣的,最後也要加上分號: 
閉包

Example #2 匿名函數變量賦值示例 

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

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

Closure 對象也會從父做用域中繼承類屬性。這些變量都必須在函數或類的頭部聲明。從父做用域中繼承變量與使用全局變量是不一樣的。全局變量存在於一個全局的範圍,不管當前在執行的是哪一個函數。而 closure 的父做用域則是聲明該 closure 的函數(不必定要是它被調用的函數)。示例以下:  函數

Example #3 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('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);

// 打出出總價格,其中有 5% 的銷售稅.
print $my_cart->getTotal(0.05) . "\n";
// 最後結果是 54.29
?>

這裏要注意理解當使用 array_walk($this->products, $callback) 調用 function($quantity, $product) use ($tax, &$total). 
這裏  $quantity, $product 分別是 $this->products 的key和value,屬於匿名函數接收到參數。
use 後面跟的是匿名函數外部做用域的變量。
this

匿名函數目前是經過 Closure 類來實現的。  更新日誌 版本        說明  5.4.0       $this 可用於匿名函數。   5.3.0       可使用匿名函數。   註釋 Note: 能夠在 closure 中使用 func_num_args() , func_get_arg() 和 func_get_args() 。 
相關文章
相關標籤/搜索