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've seen the Fibonacci example, and I really don't need to write Fibonacci sequences, so I'm still not sure if it's that useful for the kinds of tasks I encounter in writing webbish applications. So what does one do with it in "real life"?
Since there's no native support for PHP in Lambda, we'll need to provide the PHP binary for Lambda to use so that we acn execute our custom runtime code.
Use a Lambda when you need to access several services or do custom processing. As data flows through services, you use Lambdas to run custom code on that data stream. This is useful in a Kinesis Pipeline that's receiving data from things like IoT devices.
Lambda is the name of a special form that generates procedures. It takes some information about the function you want to create as arguments and it returns the procedure. It'll be easier to explain the details after you see an example.
Lambda provides a programming model that is common to all of the runtimes. The programming model defines the interface between your code and the Lambda system. You tell Lambda the entry point to your function by defining a handler in the function configuration.
Anything that requires a temporary function that you probably will only use once.
I would use them for callbacks, for functions such as:
E.g.
usort($myArray, function ($a, $b) { return $a < $b; });
Before 5.3, you'd have to..
function mySort ($a, $b) { return $a < $b; } usort($myArray, 'mySort');
Or create_function ...
usort($myArray, create_function('$a, $b', 'return $a < $b;'));
Anonymous functions (closures) can be created as local functions (thus not pollluting the global space, as Dathan suggested).
With the "use" keyword, variables that are passed to or created by the enclosing function can be used inside the closure. This is very useful in callback functions that are limited in their parameter list. The "use" variables can be defined outside the closure, eliminating the need to redefine them each time the closure is called.
function change_array($arr, $pdo) { $keys = array('a', 'c'); $anon_func = function(& $val, $key) use ($keys, $pdo) { if (in_array($key, $keys) { $pdo->query('some query using $key'); $val = $pdo->fetch(); } } arr_walk($arr, $anon_func); return $arr; } $pdo = new($dsn, $uname, $pword); $sample = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4); $sample = change_array($sample, $pdo);
(Of course, this example can be simpler without a closure, but it's just for demo.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With