zoukankan      html  css  js  c++  java
  • PHP

         现在的语言没有闭包简直都不好意思说出来。

         想要了解闭包是什么,那么就必须知道匿名函数。其实看起来他们其实差不多一个意思。

         见php RFC一句话:

      End of 2007 a patch was proposed that would add lambda functions( but without closures) to PHP. During the discussion on the mailing list, several people suggested that without support for closures, lambda functions are not useful enough to add them to PHP. This proposal describes a viable method of add lambda functions with closure support to PHP.

         大概意思是,很早以前PHP只能使用匿名函数。但是呢没有闭包的匿名函数等于没什么用处,所以后来就加上了闭包。

    1. 匿名函数有什么作用呢?

    lambda functions allow the definition of throwaway functions that are not used anywhere

     也就是说,匿名函数的作用就是能够简便快速的写那些只用一次的函数。

     如果没有匿名函数,可能会出现如下情况:

     

         如果有的话,我想大部分人都会直接写:

    return preg_replace_callback('//', funciton($match) {xxx},$text)

         这个就是匿名函数的作用。不过个人看法: 有了匿名函数之后,变量相当于有了CallBack这个类型。其实对于以前的php是一个比较大的改动,我们可以直接引用函数。我是这么理解的。

     2. Closures闭包

     Closures provide a very useful tool in order to make lambda functions even more useful.

         闭包使得匿名函数更有作用,总的来说就是给匿名函数提供了一个访问父级上下文的功能。并且通用闭包的特性就是会保存上下文中引用过的值。

         如下面的例子:引用了上下文中的$search和$replacement

          可能这样看起来并不特别,下面会详细介绍。

         值得注意的是:闭包的生命周期

    Support for references are necessary in order to achieve true closures( like javascript, where a variable originating in parent scope can be modified by closures) while copying per default fits best with the current semantics of PHP and does not cause headaches in loop( for example, when importing a loop index into a closure).

      在OOP中的Closure 默认可以访问 Class里面的 $this 指针,而不用像上面那样使用use来直接引入。

  • 相关阅读:
    MVC4学习-View(0)
    javascript与常用正则表达式
    uhfreader&rfid标签测试
    WebClient文件上传很方便哈
    NAudio的简单用法
    与wmi交互,调非托管代码,单元测试遇到的一些问题
    我在这里骑美团单车被交警罚了50元,这个地方不能骑共享单车大家留意了
    发邮件,美化table格式
    学习jwt的简单使用
    学习redis的基本使用
  • 原文地址:https://www.cnblogs.com/maxmys/p/3327247.html
Copyright © 2011-2022 走看看