PHP closure function usage

One, closure

  • 1). Closures and anonymous functions were introduced in PHP5.3.

  • 2). A closure is a function that encapsulates the state around the function when it is created. Even if the environment in which the closure is located no longer exists, the state encapsulated by the closure still exists. This is similar to the closure feature of Javascript.

  • 3). An anonymous function is a function without a name. An anonymous function can be assigned to a variable, and it can also be passed like any other PHP object. You can think of anonymous functions and closures as the same concept.

  • 4). It should be noted that the syntax used by closures is the same as that of ordinary functions, but it is actually an object pretending to be a function, an instance of the Closure class. Closures, like strings or integers, are first-class value types.

Second, the use of closures

1. Anonymous function
$变量名=functio(){  };		
2, as a callback function
1)array_filter($数组,function( $v){

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

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

Three, additional status

1). Note that PHP closures will not automatically encapsulate the state of the application like JS. In PHP, you must call the bindTo method of the closure object or use the use keyword to attach the state to the PHP closure.
<?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!

In this example, the function enclosePerson() has a $name parameter, this function returns a closure object, this closure encapsulates the $name parameter, even if the returned object out of the scope of the enclosePerson() function, it will remember Keep the value of the $name parameter, because the $name variable is still in the closure.


2). Use the use keyword to pass multiple keywords into the closure. At this time, use a comma to separate multiple parameters like the parameters of a PHP function or method.

3). PHP closure is still an object, you can use the $this keyword to get the internal state of the closure. There is a __invoke() magic method and bindTo() method in the default state of the closure.

4) The .bindTo() method adds some interesting things to the closure.

We can use this method to bind the internal state of the Closure object to other objects. The second parameter of the bindTo() method can specify the PHP class to which the object to which the closure belongs, so that we can access the protected and private member variables of this class.

<?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;
    }
}

We bind the routing callback to the current App instance, so that the state of the App instance can be processed in the callback function.

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

Guess you like

Origin blog.csdn.net/weixin_43272542/article/details/113125860