Modern PHP closure closures

Source: Internet
Author: User

* Use closures in the Array_map () function

<?php$numbersplusone = Array_map (function ($number) {   return $number + 1;}, [[i]];p rint_r ($numbersPlusOne);

  

$ PHP numbersplusone.php

  

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

* Append the status of closures with the USE keyword

<?phpfunction Encloseperson ($name) {    //use can pass multiple parameters into the closure    return function ($doCommand) used ($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!

* Use the BindTo method to attach the status of closures

<?phpclass App {protected $routes = [];    protected $responseStatus = ' OK ';    protected $responseContentType = ' text/html ';    protected $responseBody = ' Hello world '; Public Function Addroute ($routePath, $routeCallBack) {$this->routes[$routePath] = $routeCallBack->bindto ($th    is, __class__);            The 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; cha    Rset=utf8 '; $this->responsebody = ' {' name ': ' Josh '} ';}); $app->dispatch ('/users/josh '); Echo php_eol;//{"NamE ":" Josh "} 

  

Modern PHP closure closures

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.