PHP lambda 与 闭包

WBOY
Release: 2016-06-23 14:33:30
Original
1021 people have browsed it

lambda、

我自己的理解,lambda就是把方法名保存到一个变量里面去调用方法,典型的create_function所返回的就是lambda方法。

1 $newfunc = create_function('$a', 'echo "what u put in is " . $a;');2 $newfunc('aaaaa');
Copy after login

更简单地可以自己去写lambda方法的名称,然后用以这种形式去调用。

1 function dump($a){2      var_dump($a);3 }4 $a = 'dump';5 $a('321');
Copy after login

闭包、

这里单单从语法上说一下PHP的闭包,考虑下面的代码:

 1 class ClosureTest{ 2      public $multiplier; 3      public function __construct($multilier){ 4           $this->multiplier= $multilier; 5      } 6   7      public function getClosure(){ 8           $self = $this; 9           return function($number) use($self) {10                return $number * $self->multiplier;11           };12      }13 }14 15 $test = new ClosureTest(10);16 $x = $test->getClosure();17 echo $x(8);18 $test->multiplier= 11;19 echo $x(8);
Copy after login

 

最后结果为:8088.

必须用到use向闭包中传值,否则在调用时将提示变量未被定义的Notice。

闭包无法直接传递$this指针,所以这里先将$this保存在了$self中。

还有一点代码中没有体现出来,通过use传类成员到闭包中必须通过引用传递,否则在后来修改改成员的值后比包中的值不会被改变。

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template