什麼是php閉包?閉包用法執行個體詳解

來源:互聯網
上載者:User
這篇文章主要介紹了PHP 閉包詳解及執行個體代碼的相關資料,需要的朋友可以參考下

閉包和匿名函數在PHP5.3.0中引入的。

閉包是指:建立時封裝周圍狀態的函數。即使閉包所處的環境不存在了,閉包中封裝的狀態依然存在。

理論上,閉包和匿名函數是不同的概念。但是PHP將其視作相同概念。

實際上,閉包和匿名函數是偽裝成函數的對象。他們是Closure類的執行個體。

閉包和字串、整數一樣,是一等實值型別。

建立閉包

<?php$clousre = function ($name) {return 'Hello ' . $name;};echo $closure('nesfo');

我們之所以能調用$closure變數,是因為這個變數的值是一個閉包,而且閉包對象實現了invoke()魔術方法。只要變數名後有(),PHP就會尋找並調用invoke()方法。通常會把PHP閉包當作函數的回調使用。array_map(), preg_replace_callback()方法都會用到回呼函數,這是使用閉包的最佳時機!

舉個例子:

<?php$numbersPlusOne = array_map(function ($number) {return $number + 1;}, [1, 2, 3]);print_r($numbersPlusOne);

得到結果:

[2, 3, 4]

在閉包出現之前,只能單獨建立具名函數,然後使用名稱引用那個函數。這麼做,代碼執行會稍微慢點,而且把回調的實現和使用情境隔離了。

<?phpfunction incrementNum ($number) {return $number + 1;}$numbersPlusOne = array_map('incrementNum', [1, 2, 3]);print_r($numbersPlusOne);

附加狀態

匿名函數不止可以當回調使用,還可以為PHP附加並封裝狀態。

PHP中,必須手動調用閉包對象的bindTo()方法或者使用use關鍵字,才能把狀態附加到PHP閉包上。

<?phpfunction enclosePerson ($name) {return function ($doCommand) use ($name) {return $name . ', ' . $doCommand;}}$clay = enclosePerson('Clay');echo $clay('get me sweet tea!');

得到結果:

"Clay, get me sweet tea!"

PHP閉包是對象,每個閉包執行個體都可以使用$this關鍵字擷取閉包的內部狀態。閉包對象的預設狀態沒什麼用,只有invoke()方法和bindTo方法而已。

我們可以使用bindTo()這個方法,將Closure對象的內部狀態綁定到其它對象上。

bindTo()方法的第二個參數:其作用是指定綁定閉包的那個對象所屬的PHP類。因此,閉包可以訪問綁定閉包的對象中受保護和私人的成員。

PHP架構經常使用bindTo()方法把路由URL映射到匿名回呼函數上。這麼做可以在這個匿名函數中使用$this關鍵字引用重要的應用對象。

使用bindTo()方法附加閉包狀態

<?phpclass App{protected $routes = [];protected $responseStatus = '200 OK';protected $responseContentType = 'text/html';protected $responseBody = 'Hello world';public function addRoute($routePath, $routeCallback){$this->routes[$routePath] = $routeCallback->bindTo($this, CLASS);}public function dispatch($currentPath){foreach($this->routes as $routePath => $callback){if ($routePath === $currentPath) {$callback();}}header('HTTP/1.1' . $this->responseStatus);header('Content-type: ' . $this->responseContentType);header('Content-length' . mb_strlen($this->responseBody));echo $this->responseBody;}}
<?php$app = new App();$app->addRoute('/user/nesfo', function () {$this->responseContentType = 'application/json; charset=utf8';$this->responseBody = '{"name": "nesfo"}';});$app->dispatch('/user/nesfo');

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.