Closure,匿名函數,是php5.3的時候引入的,又稱爲Anonymous functions。字面意思也就是沒有定義名字的函數。好比如下代碼(文件名是do.php)php
function A() { return 100; }; function B(Closure $callback) { return $callback(); } $a = B(A()); print_r($a);
//輸出:Fatal error: Uncaught TypeError: Argument 1 passed to B() must be an instance of Closure, integer given, called in
D:\web\test\do.php on line 11 and defined in
D:\web\test\do.php:6 Stack trace: #0
D:\web\test\do.php(11): B(100) #1 {main} thrown in
D:\web\test\do.php on line 6
這裏的A()永遠沒有辦法用來做爲B的參數,由於A它並非「匿名」函數。
因此應該改爲這樣:html
$f = function () { return 100; }; function B(Closure $callback) { return $callback(); } $a = B($f); print_r($a);//輸出100 $func = function( $param ) { echo $param; }; $func( 'hello word' ); //輸出:hello word
實現閉包
將匿名函數在普通函數中當作參數傳入,也能夠被返回。這就實現了一個簡單的閉包。
下邊我舉三個例子:web
//例一 //在函數裏定義一個匿名函數,而且調用它 function printStr() { $func = function( $str ) { echo $str; }; $func( ' hello my girlfriend ! ' ); } printStr();//輸出 hello my girlfriend !
//例二 //在函數中把匿名函數返回,而且調用它 function getPrintStrFunc() { $func = function( $str ) { echo $str; }; return $func; } $printStrFunc = getPrintStrFunc(); $printStrFunc( ' do you love me ? ' );//輸出 do you love me ?
//例三 //把匿名函數當作參數傳遞,而且調用它 function callFunc( $func ) { $func( ' no!i hate you ' ); } $printStrFunc = function( $str ) { echo $str.'<br>'; }; callFunc( $printStrFunc ); //也能夠直接將匿名函數進行傳遞。若是你瞭解js,這種寫法可能會很熟悉 callFunc( function( $str ) { echo $str; //輸出no!i hate you });
鏈接閉包和外界變量的關鍵字:USE
閉包能夠保存所在代碼塊上下文的一些變量和值。PHP在默認狀況下,匿名函數不能調用所在代碼塊的上下文變量,而須要經過使用use關鍵字。
換一個例子看看(好吧,我缺錢,我很俗):閉包
function getMoney() { $rmb = 1; $dollar = 8; $func = function() use ( $rmb ) { echo $rmb; echo $dollar; }; $func(); } getMoney(); //輸出:1 並報錯$dollar未聲明 由於use 沒有加進來
能夠看到,dollar沒有在use關鍵字中聲明,在這個匿名函數裏也就不能獲取到它,因此開發中要注意這個問題。
有人可能會想到,是否能夠在匿名函數中改變上下文的變量,但我發現好像是不能夠的:函數
function getMoney() { $rmb = 1; $func = function() use ( $rmb ) { echo $rmb.'<br>'; $rmb++;//把$rmb的值加1 }; $func(); echo $rmb; } getMoney(); //輸出: //1 //1
額,原來use所引用的也只不過是變量的一個副本clone而已。可是我想要徹底引用變量,而不是複製呢?要達到這種效果,其實在變量前加一個 & 符號就能夠了:oop
function getMoney() { $rmb = 1; $func = function() use ( &$rmb ) { echo $rmb.'<br>'; $rmb++;//把$rmb的值加1 }; $func(); echo $rmb; } getMoney(); //輸出: //1 //2
好,這樣匿名函數就能夠引用上下文的變量了。若是將匿名函數返回給外界,匿名函數會保存use所引用的變量,而外界則不能獲得這些變量,這樣造成‘閉包'這個概念可能會更清晰一些。
根據描述咱們再改變一下上面的例子:this
function getMoneyFunc() { $rmb = 1; $func = function() use ( &$rmb ) { echo $rmb.'<br>'; $rmb++;//把$rmb的值加1 }; return $func; } $getMoney = getMoneyFunc(); $getMoney(); $getMoney(); $getMoney(); //輸出: //1 //2 //3
(就是函數體釋放了,可是裏面的匿名函數或上下班變量未釋放,依然在棧區內)spa
好吧,扯了這麼多,那麼若是咱們要調用一個類裏面的匿名函數呢?直接上demo.net
class A { public static function testA() { return function($i) { //返回匿名函數 return $i+100; }; } } function B(Closure $callback) { return $callback(200); } $a = B(A::testA()); print_r($a);//輸出 300
其中的A::testA()返回的就是一個無名funciton。
綁定的概念
上面的例子的Closure只是全局的的匿名函數,好了,那咱們如今想指定一個類有一個匿名函數。也能夠理解說,這個匿名函數的訪問範圍再也不是全局的了,而是一個類的訪問範圍。
那麼咱們就須要將「一個匿名函數綁定到一個類中」。code
上面的例子中,f這個匿名函數中莫名奇妙的有個this,這個this關鍵詞就是說明這個匿名函數是須要綁定在類中的。
綁定以後,就好像A中有這麼個函數同樣,可是這個函數是public仍是private,bind的最後一個參數就說明了這個函數的可調用範圍。
上面你們看到了bindTo,咱們來看官網的介紹
(PHP 5 >= 5.4.0, PHP 7) Closure::bind — 複製一個閉包,綁定指定的$this對象和類做用域。 說明 public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] ) 這個方法是 Closure::bindTo() 的靜態版本。查看它的文檔獲取更多信息。 參數 closure 須要綁定的匿名函數。 newthis 須要綁定到匿名函數的對象,或者 NULL 建立未綁定的閉包。 newscope 想要綁定給閉包的類做用域,或者 'static' 表示不改變。若是傳入一個對象,則使用這個對象的類型名。 類做用域用來決定在閉包中 $this 對象的 私有、保護方法 的可見性。(備註:能夠傳入類名或類的實例,默認值是 'static', 表示不改變。) 返回值: 返回一個新的 Closure 對象 或者在失敗時返回 FALSE
class A { private static $sfoo = 1; private $ifoo = 2; } $cl1 = static function() { return A::$sfoo; }; $cl2 = function() { return $this->ifoo; }; $bcl1 = Closure::bind($cl1, null, 'A'); $bcl2 = Closure::bind($cl2, new A(), 'A'); echo $bcl1(), "\n";//輸出 1 echo $bcl2(), "\n";//輸出 2
咱們再來看個例子加深下理解:
class A { public $base = 100; } class B { private $base = 1000; } class C { private static $base = 10000; } $f = function () { return $this->base + 3; }; $sf = static function() { return self::$base + 3; }; $a = Closure::bind($f, new A); print_r($a());//這裏輸出103,綁定到A類 echo PHP_EOL; $b = Closure::bind($f, new B , 'B'); print_r($b());//這裏輸出1003,綁定到B類 echo PHP_EOL; $c = $sf->bindTo(null, 'C'); //注意這裏:使用變量#sf綁定到C類,默認第一個參數爲null print_r($c());//這裏輸出10003
咱們再看一個demo:
/** * 複製一個閉包,綁定指定的$this對象和類做用域。 * * @author fantasy */ class Animal { private static $cat = "加菲貓"; private $dog = "汪汪隊"; public $pig = "豬豬俠"; } /* * 獲取Animal類靜態私有成員屬性 */ $cat = static function() { return Animal::$cat; }; /* * 獲取Animal實例私有成員屬性 */ $dog = function() { return $this->dog; }; /* * 獲取Animal實例公有成員屬性 */ $pig = function() { return $this->pig; }; $bindCat = Closure::bind($cat, null, new Animal());// 給閉包綁定了Animal實例的做用域,但未給閉包綁定$this對象 $bindDog = Closure::bind($dog, new Animal(), 'Animal');// 給閉包綁定了Animal類的做用域,同時將Animal實例對象做爲$this對象綁定給閉包 $bindPig = Closure::bind($pig, new Animal());// 將Animal實例對象做爲$this對象綁定給閉包,保留閉包原有做用域 echo $bindCat(),'<br>';// 輸出:加菲貓,根據綁定規則,容許閉包經過做用域限定操做符獲取Animal類靜態私有成員屬性 echo $bindDog(),'<br>';// 輸出:汪汪隊, 根據綁定規則,容許閉包經過綁定的$this對象(Animal實例對象)獲取Animal實例私有成員屬性 echo $bindPig(),'<br>';// 輸出:豬豬俠, 根據綁定規則,容許閉包經過綁定的$this對象獲取Animal實例公有成員屬性
經過上面的幾個例子,其實匿名綁定的理解就不難了....咱們在看一個擴展的demo(引入trait特性)
http://php.net/manual/zh/language.oop5.traits.php 代碼複用到其餘地方 use一下就行 多個用,分開
/** * 給類動態添加新方法 * * @author fantasy */ trait DynamicTrait { /** * 自動調用類中存在的方法 */ public function __call($name, $args) { if(is_callable($this->$name)){ return call_user_func($this->$name, $args); }else{ throw new \RuntimeException("Method {$name} does not exist"); } } /** * 添加方法 */ public function __set($name, $value) { $this->$name = is_callable($value)? $value->bindTo($this, $this): $value; } } /** * 只帶屬性不帶方法動物類 * * @author fantasy */ class Animal { use DynamicTrait; private $dog = '汪汪隊'; } $animal = new Animal; // 往動物類實例中添加一個方法獲取實例的私有屬性$dog $animal->getdog = function() { return $this->dog; }; echo $animal->getdog();//輸出 汪汪隊
好比如今咱們用如今購物環境
/** * 一個基本的購物車,包括一些已經添加的商品和每種商品的數量 * * @author fantasy */ class Cart { // 定義商品價格 const PRICE_BUTTER = 10.00; const PRICE_MILK = 30.33; const PRICE_EGGS = 80.88; protected $products = array(); /** * 添加商品和數量 * * @access public * @param string 商品名稱 * @param string 商品數量 */ public function add($item, $quantity) { $this->products[$item] = $quantity; } /** * 獲取單項商品數量 * * @access public * @param string 商品名稱 */ public function getQuantity($item) { return isset($this->products[$item]) ? $this->products[$item] : FALSE; } /** * 獲取總價 * * @access public * @param string 稅率 */ public function getTotal($tax) { $total = 0.00; $callback = function ($quantity, $item) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($item)); //調用以上對應的常量 $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2); } } $my_cart = new Cart; // 往購物車裏添加商品及對應數量 $my_cart->add('butter', 10); $my_cart->add('milk', 3); $my_cart->add('eggs', 12); // 打出出總價格,其中有 3% 的銷售稅. echo $my_cart->getTotal(0.03);//輸出 1196.4
參考:http://www.jb51.net/article/79350.htm
http://www.jb51.net/article/61261.htm
https://www.cnblogs.com/lizhi-/articles/7204146.html
下一篇文章: http://www.cnblogs.com/fps2tao/p/8727482.html