What use is lambda in PHP?

后端 未结 5 1724
南方客
南方客 2020-12-12 21:40

The lambda anonymous function is part of PHP 5.3. What use does it have? Is there anything that one can only do with lambda? Is lambda better for certain tasks?

I\'

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 22:34

    There are some use cases that are made more convenient by lambdas. For instance, if a method uses a callback, using a lambda for that callback means you don't have to define a "real" function somewhere to handle it. So, lambdas keep your code cleaner.

    As with the above, lambdas can be used as "short-lived" functions. For instance, sorting algorithms typically only need to know if variable a is less than variable b for any combination of a and b. To make a generic sorting algorithm that's capable of handling any class of objects, you might make your sort function definition such that it accepts a function to use as a comparator. Providing a lambda as the comparator function means that you can define your sort behavior on a per-call basis, rather than having to define a "real" function that will live for the lifetime of your script just to handle this one sorting case.

提交回复
热议问题