首页 > 编程语言 >php关于闭包(匿名函数)的理解

php关于闭包(匿名函数)的理解

时间:2023-04-04 15:35:26浏览次数:45  
标签:闭包 product 函数 作用域 匿名 php Example 变量


匿名函数(Anonymous functions),也叫闭包函数(closures),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值。当然,也有其它应用的情况。

匿名函数目前是通过 Closure 类来实现的。

Example #1 匿名函数示例

<?php
 echo preg_replace_callback('~-([a-z])~', function ($match) {
     return strtoupper($match[1]);
 }, 'hello-world');
 // 输出 helloWorld
 ?>

闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的,最后也要加上分号:

Example #2 匿名函数变量赋值示例

<?php
 $greet = function($name)
 {
     printf("Hello %s\r\n", $name);
 };

 $greet('World');
 $greet('PHP');
 ?>

闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。 PHP 7.1 起,不能传入此类变量: superglobals、 $this 或者和参数重名。【use使用的是参数的副本而已,如果想要真实值,必须使用&】

Example #3 从父作用域继承变量

<?php
 $message = 'hello';

 // 没有 "use"
 $example = function () {
     var_dump($message);
 };
 echo $example();

 // 继承 $message
 $example = function () use ($message) {
     var_dump($message);
 };
 echo $example();

 // Inherited variable's value is from when the function
 // is defined, not when called
 $message = 'world';
 echo $example();

 // Reset message
 $message = 'hello';

 // Inherit by-reference
 $example = function () use (&$message) {
     var_dump($message);
 };
 echo $example();

 // The changed value in the parent scope
 // is reflected inside the function call
 $message = 'world';
 echo $example();

 // Closures can also accept regular arguments
 $example = function ($arg) use ($message) {
     var_dump($arg . ' ' . $message);
 };
 $example("hello");
 ?>

以上例程的输出类似于:


Notice: Undefined variable: message in /example.php on line 6 NULL string(5) "hello" string(5) "hello" string(5) "hello" string(5) "world" string(11) "hello world"


这些变量都必须在函数或类的头部声明。 从父作用域中继承变量与使用全局变量是不同的。全局变量存在于一个全局的范围,无论当前在执行的是哪个函数。而 闭包的父作用域是定义该闭包的函数(不一定是调用它的函数)。示例如下:

Example #4 Closures 和作用域

<?php
 // 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。
 // 其中有一个方法用来计算购物车中所有商品的总价格,该方法使
 // 用了一个 closure 作为回调函数。
 class Cart
 {
     const PRICE_BUTTER  = 1.00;
     const PRICE_MILK    = 3.00;
     const PRICE_EGGS    = 6.95;

     protected   $products = array();
     
     public function add($product, $quantity)
     {
         $this->products[$product] = $quantity;
     }
     
     public function getQuantity($product)
     {
         return isset($this->products[$product]) ? $this->products[$product] :
                FALSE;
     }
     
     public function getTotal($tax)
     {
         $total = 0.00;
         
         $callback =
             function ($quantity, $product) use ($tax, &$total)
             {
                 $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                     strtoupper($product));
                 $total += ($pricePerItem * $quantity) * ($tax + 1.0);
             };
         
         array_walk($this->products, $callback);
         return round($total, 2);;
     }
 }

 $my_cart = new Cart;

 // 往购物车里添加条目
 $my_cart->add('butter', 1);
 $my_cart->add('milk', 3);
 $my_cart->add('eggs', 6);

 // 打出出总价格,其中有 5% 的销售税.
 print $my_cart->getTotal(0.05) . "\n";
 // 最后结果是 54.29
 ?>

Example #5 Automatic binding of $this

<?php

 class Test
 {
     public function testing()
     {
         return function() {
             var_dump($this);
         };
     }
 }

 $object = new Test;
 $function = $object->testing();
 $function();
     
 ?>

以上例程会输出:


object(Test)#1 (0) { }


以上例程在PHP 5.3中的输出:


Notice: Undefined variable: this in script.php on line 8 NULL

标签:闭包,product,函数,作用域,匿名,php,Example,变量
From: https://blog.51cto.com/huangama8/6168722

相关文章

  • PHP正则表达式
    验证邮箱格式复制代码//验证邮箱格式functioncheckEmail($email){if(!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)){returnfalse;}else{returntrue;}}复制代码验证URL复制代码//验证URLfunctioncheckWebsite($we......
  • PHP 判断数组是否为空的方法
    1.isset功能:判断变量是否被初始化说明:它并不会判断变量是否为空,并且可以用来判断数组中元素是否被定义过注意:当使用isset来判断数组元素是否被初始化过时,它的效率比array_key_exists高4倍左右<?php$a='';$a['c']='';if(!isset($a))echo'$a未被初始化'."";if......
  • Python基础【20】匿名函数和可迭代函数
      reduce函数和map函数:   ......
  • 2023年php面试题
                                      Php面试题1、isset和empty的区别?Isset测试变量是否被赋值,如果这个变量没被赋值,则返回false,empty是判断变量是否为空,当赋值为0,null,’’,返回true为真。他们之间最大的区别就是当一个变量被赋值0时,empty判......
  • centos7/centos8 PHP7.2/php7.3/php7.4 以上版本 源码安装 编译
    yumupdate  1、安装依赖包[root@centos7_4~]#yum-yinstallphp-mcryptlibmcryptlibmcrypt-devel autoconf freetypegdlibmcryptlibpnglibpng-devellibjpeglibxml2libxml2-develzlibcurlcurl-develre2cnet-snmp-devellibjpeg-develphp-ldapopenl......
  • PHP 实现动态实时输出
    #设置执行时间不限时 set_time_limit(0);#清除并关闭缓冲,输出到浏览器之前使用这个函数。ob_end_clean();#控制隐式缓冲泻出,默认off,打开时,对每个print/echo或者输出命令的结果都发送到浏览器。ob_implicit_flush(1);header(“Content-type:text/html;charset=utf-8″);ob_......
  • 宝塔安装PHP8.0不成功的解决办法
    使用宝塔安装PHP8.0的时候提示安装完成后,在软件列表里PHP8.0是正在安装和未安装执行死循环错误提示:configure:error:Packagerequirements(libjpeg)werenotmet查看错误提示路径:宝塔后台打开消息盒子,点击“执行日志”,这里会有具体错误提示,错误如下:Nopackage'libjpeg'f......
  • eyoucms 去掉 index.php后缀
    针对不同服务器、虚拟空间,运行PHP的环境也有所不同,目前主要分为:Nginx、apache、IIS以及其他服务器。下面分享如何去掉URL上的index.php字符,记得在管理后台清除缓存,对于一些ECS服务器可能要重启nginx等服务!【Nginx服务器】在原有的nginx重写文件里新增以下代码片段:location/......
  • php遇到failed to open stream: Permission denied
    Uncaughtexception'think\exception\ErrorException'withmessage'error_log(/www/api/public/../runtime/log/201611/29.log):failedtoopenstream:Permissiondenied'in/www/api/thinkphp/library/think/log/driver/File.php当赋权限后当天可以,但是......
  • php-websocket hyperf/websocket-server/client 客户端和服务器实时双向数据传输
    WebSocket服务WebSocket是一种通信协议,可在单个TCP连接上进行全双工通信。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocketAPI中,浏览器和服务器只需要完成一次握手,两者之间就可以建立持久性的连接,并进行双向数据传输。Hyperf......