zoukankan      html  css  js  c++  java
  • modern php closure 闭包

    * 在array_map()函数中使用闭包

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

      

    $ php numbersPlusOne.php
    

      

    Array
    (
    [0] => 2
    [1] => 3
    [2] => 4
    )

    * 使用use关键字附加闭包的状态

    <?php
    
    function enclosePerson($name) {
        // use 可以把多个参数传入闭包
        return function($doCommand) use ($name) {
            return sprintf('%s, %s'.PHP_EOL, $name, $doCommand);
        };
    }
    
    $clay = enclosePerson('Clay');
    
    echo $clay('get me some sweet tea!');
    

      Clay, get me some sweet tea!

    * 使用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($currrentPath) {
            foreach ($this->routes as $routePath => $callback) {
                if ($routePath === $currrentPath) {
                    $callback();
                }
            }
            header('HTTP/1.1 ', $this->responseStatus);
            header('Content-Type: ', $this->responseContentType);
            header('Content-length: ', mb_strlen($this->responseBody));
            echo $this->responseBody;
        }
    }
    
    $app = new App();
    $app->addRoute('/users/josh', function() {
        $this->responseContentType = 'application/json; charset=utf8';
        $this->responseBody = '{"name": "Josh"}';
    });
    
    $app->dispatch('/users/josh');
    echo PHP_EOL;
    // {"name": "Josh"}
    

      

  • 相关阅读:
    pat甲级1004 Counting Leaves
    pat甲级1003 Emergency
    pat甲级1002 A+B for Polynomials
    pat甲级1001 A+B Format
    【转载】sql注入之入门
    JavaScript基础学习笔记
    django 安装
    python web编程CGI
    python urllib库
    python数据库编程
  • 原文地址:https://www.cnblogs.com/mingzhanghui/p/9314182.html
Copyright © 2011-2022 走看看