PHP's functional programming relies on functions. Functions in PHP provide organized, reusable code to perform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes the declaration and utilization of functions, arguments, parameters, return statements and scope in PHP.
An anonymous function is just a function that doesn't have a name.
In PHP, an anonymous function is treated like an expression and for this reason, it should be ended with a semicolon ;.
An anonymous function should be assigned to a variable.
Or it should be passed as parameter of another function.
Or even been returned from another function.
Self-executing anonymous functions:
Passing an argument into self-executing anonymous functions:
Assignment to variables
Anonymous functions can be assigned to variables for use as parameters where a callback is expected:
These variables can also be used as standalone function calls:
A closure is an anonymous function that can't access outside scope.
When defining an anonymous function as such, you're creating a "namespace" for that function. It currently only has access to that namespace.
It doesn't have access to any external variables. To grant this permission for this namespace to access external variables, you need to introduce it via closures (use()).
This is heavily attributed to PHP's tight variable scoping - If a variable isn't defined within the scope, or isn't brought in with global then it does not exist.
Inheriting variables from the parent scope is not the same as using
global variables. Global variables exist in the global scope, which is
the same no matter what function is executing.
The parent scope of a
closure is the function in which the closure was declared (not
necessarily the function it was called from).
Depending on where the user-defined callback function was defined there are different ways to pass them:
Object Oriented style:
Object Oriented style using a static method:
A pure function is a function that, given the same input, will always return the same output and are side-effect free.
Some side-effects are changing the filesystem, interacting with databases, printing to the screen.
In PHP, an anonymous function has its own scope like any other PHP function.
Using built-in functions as callbacks
In functions taking callable as an argument, you can also put a string with PHP built-in function. It's common to use trim as array_map parameter to remove leading and trailing whitespace from all strings in the array.
Using outside variables
The use construct is used to import variables into the anonymous function's scope:
Variables can also be imported by reference:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0