分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

modern php closure 闭包

发布时间:2023-09-06 02:04责任编辑:赖小花关键词:闭包

* 在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关键字附加闭包的状态

<?phpfunction 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方法附加闭包的状态

<?phpclass 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"}

  

modern php closure 闭包

原文地址:https://www.cnblogs.com/mingzhanghui/p/9314182.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved