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来直接引入。

  • 相关阅读:
    mysql新建用户的方法
    工具网站
    如何做好站内锚文本?
    js 创建对象与继承
    js tips
    js作用域链 js没有块级作用域
    css
    instanceof
    问题
    传递,引用副本传递
  • 原文地址:https://www.cnblogs.com/maxmys/p/3327247.html
Copyright © 2011-2022 走看看