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 é­åèµæçèµææ´çï¼å续继续补åç¸å³èµæ谢谢大家对æ¬ç«çæ¯æï¼

相关推荐