Home > Article > Backend Development > Use of php anonymous functions
The introduction of anonymous functions
Before the emergence of anonymous functions, all functions needed to be named before they could be used
Sometimes a function may only need to be used once. In this case, using an anonymous function will make the code more concise and intuitive, and also prevent the function from being used in other places
(Free learning video tutorial sharing: php video tutorial)
Definition and use of anonymous functions
PHP will close They are regarded as equivalent concepts to anonymous functions (collectively referred to as anonymous functions in this article). They are essentially objects disguised as functions.
The essence of anonymous functions is objects, so just like objects, anonymous functions can be assigned to a variable
All anonymous functions are Closure objects Instance
The object has no parent scope to speak of, so you need to use use to manually declare the variables used
If you want the variables in the anonymous function to take effect, you need to use reference pass-by-value
Starting from PHP 5.4, when using an anonymous function in a class, the $this of the anonymous function will Automatically bind to the current class
#If you don’t want automatic binding to take effect, you can use a static anonymous function
The essence of anonymous functions
The essence of anonymous functions is the Closure object, including the following five methods
__construct - Prevent anonymous functions from being Instantiation
Closure::bindTo - Copies the current anonymous function object, binding the specified $this object and class scope. In layman's terms, it means manually binding an anonymous function to a specified object. Using this, you can extend the functionality of the object.
Closure::bind - A static version of the bindTo method, there are two usages:
Usage 1: To achieve the same effect as the bindTo method
Usage 2: Bind the anonymous function to the class (rather than the object). Remember to set the second parameter to null
call - The new call method in PHP 7 can bind and call anonymous functions. In addition to simpler syntax, the performance is also higher
fromCallable - will give A certain callable function is converted into an anonymous function
##fromCallable is equivalent to There is one thing that needs special attention here. , whether it is a closure converted fromCallable or a closure obtained using reflection, when using bindTo, if the second parameter specifies the binding class, an error will be reportedRecommended related article tutorials: php tutorial
The above is the detailed content of Use of php anonymous functions. For more information, please follow other related articles on the PHP Chinese website!