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]
å¨éååºç°ä¹åï¼åªè½åç¬å建å·åå½æ°ï¼ç¶å使ç¨å称å¼ç¨é£ä¸ªå½æ°ãè¿ä¹åï¼ä»£ç æ§è¡ä¼ç¨å¾®æ¢ç¹ï¼èä¸æåè°çå®ç°å使ç¨åºæ¯é离äºã
<?php function incrementNum ($number) { return $number + 1; } $numbersPlusOne = array_map('incrementNum', [1, 2, 3]); print_r($numbersPlusOne);
éå ç¶æ
å¿åå½æ°ä¸æ¢å¯ä»¥å½åè°ä½¿ç¨ï¼è¿å¯ä»¥ä¸ºPHPéå 并å°è£ç¶æã
PHPä¸ï¼å¿é¡»æå¨è°ç¨éå对象çbindTo()æ¹æ³æè使ç¨useå³é®åï¼æè½æç¶æéå å°PHPéåä¸ã
<?php function 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()æ¹æ³éå éåç¶æ
<?php class 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');
以ä¸å°±æ¯å¯¹PHP éåèµæçèµææ´çï¼åç»ç»§ç»è¡¥åç¸å³èµæ谢谢大家对æ¬ç«çæ¯æï¼