PHP Lambda and closures

Source: Internet
Author: User
Lambda

My own understanding, lambda is to save the method name into a variable to invoke the method, the typical create_function is to return the lambda method.

1 $newfunc = create_function (' $a ', ' echo ' What U put on is '. $a; '); 2 $newfunc (' aaaaa ');

It's easier to write the name of the lambda method yourself, and then call it in this form.

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

Closures,

Here's a simple syntax for PHP closures, 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           };      }13}14 $test = new Closuretest, $x = $test->getclosure (); Echo $x (8); $test->multiplier= 11;19 echo $x (8);

The final result is: 8088.

The use must be used to pass a value to the closure, otherwise the notice will be prompted when the variable is not defined.

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

It is also not shown in the code that the use of a class member into a closure must be passed by reference, otherwise the value of the changed member will not be changed later than in the package.

  • 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.