PHP - 闭包Closure和lambda function

     如今的语言没有闭包简直都很差意思说出来。javascript

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

     见php RFC一句话:java

  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只能使用匿名函数。可是呢没有闭包的匿名函数等于没什么用处,因此后来就加上了闭包。ide

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

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

 也就是说,匿名函数的做用就是可以简便快速的写那些只用一次的函数。this

 若是没有匿名函数,可能会出现以下状况:spa

 

     若是有的话,我想大部分人都会直接写:指针

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

相关文章
相关标签/搜索