PHP闭包函数用法

一、闭包

  • 1).闭包和匿名函数在PHP5.3中被引入。

  • 2).闭包是指在创建时封装函数周围状态的函数,即使闭包所在的环境不存在了,闭包封装的状态依然存在,这一点和Javascript的闭包特性很相似。

  • 3).匿名函数就是没有名称的函数,匿名函数可以赋值给变量,还可以像其他任何PHP对象一样传递。可以将匿名函数和闭包视作相同的概念。

  • 4).需要注意的是闭包使用的语法和普通函数相同,但是他其实是伪装成函数的对象,是Closure类的实例。闭包和字符串或整数一样,是一等值类型。

二、闭包使用

1,匿名函数
$变量名=functio(){  };		
2,作为回调函数
1)array_filter($数组,function( $v){

					规则	
					
		});
		根据规则筛选数组内容
2)$numbersPlusOne = array_map(function($number) {

    return $number + 1;
    
	}, [1, 2, 3]);
	
	根据函数内容,作用到数组每个值中,并且返回新数组

三,附加状态

1).注意PHP闭包不会真的像JS一样自动封装应用的状态,在PHP中必须调用闭包对象的bindTo方法或者使用use关键字,把状态附加到PHP闭包上。
<?php
function enclosePerson($name)
{
    return function ($doCommand) use ($name) {
        return sprintf('%s , %s', $name, $doCommand);
   } 
}
//把字符串“Clay”封装在闭包中
$clay = enclosePerson('Clay');
//传入参数,调用闭包
echo $clay('get me sweat tea!'); // Clay, get me sweat tea!

在这个例子中,函数enclosePerson()有一个$name参数,这个函数返回一个闭包对象,这个闭包封装了 $name参数,即便返回的对象跳出了enclosePerson()函数的作用域,它也会记住$name参数的值,因为 $name变量仍然在闭包中。


2).使用use关键字可以把多个关键字传入闭包,此时要想像PHP函数或方法的参数一样,使用逗号分割多个参数。

3).PHP闭包仍然是对象,可以使用$this关键字获取闭包的内部状态。闭包的默认状态里面有一个__invoke()魔术方法和bindTo()方法。

4).bindTo()方法为闭包增加了一些有趣的东西。

我们可以使用这个方法把Closure对象内部状态绑定到其他对象上。bindTo()方法的第二个参数可以指定绑定闭包的那个对象所属的PHP类,这样我们就可以访问这个类的受保护和私有的成员变量。

<?php
class App
{
    protected $route = array();
    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;
    }
}

我们把路由回调绑定到了当前的App实例上,这样就可以在回调函数中处理App实例的状态了。

<?php
$app = new App();
$app->addRoute('/users/xiaoxiao', function () {
    $this->responseContentType = 'application/json;charset=utf8';
    $this->responseBody = '{"name" : "xiaoxiao"}';
});
$app->dispatch('/users/xiaoxiao');

猜你喜欢

转载自blog.csdn.net/weixin_43272542/article/details/113125860
今日推荐