Phplam and closure

Source: Internet
Author: User
Phplamlambda and closure lambda,

In my own understanding, lambda saves the method name to a variable to call the method. a typical create_function returns the lambda method.

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

You can simply write the name of the lambda method and call it in this form.

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

Closure,

Here, let's just talk about the PHP closure from the syntax and consider the following code:

 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);

The final result is 8088.

Use must be used to transmit values to the closure. Otherwise, the variable's undefined Notice will be prompted during the call.

The closure cannot directly pass the $ this pointer, so $ this is saved in $ self first.

Another piece of code is not reflected. the class member passed to the closure through use must be passed through reference. Otherwise, the value of the modified member will not be changed after it is modified.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.