Home >Backend Development >PHP Problem >Advantages and disadvantages of php closures
Closure function: Temporarily create a function without a name, often used as a callback function. (Recommended learning: PHP video tutorial)
In layman’s terms: child functions can use local variables in the parent function. This behavior is called closure.
Anonymous function assignment
$demo=function($str){ echo $str; } $demo('hello,world');
Closures can inherit variables from the parent scope, and any variables of this type should be passed in using the use language structure.
$message='hello'; $example=function() use ($message){ var_dump($message); }; echo $example();
Advantages of closure:
Can read variables inside the function;
Let these variables always exist in memory and will not be recycled by the garbage collection mechanism after the call is completed
Disadvantages of closures:
As the saying goes, the opposite is true. Since closures will save the variables in the function in memory and consume a lot of memory, closures cannot be abused. The solution is to delete unused local variables before exiting the function.
The above is the detailed content of Advantages and disadvantages of php closures. For more information, please follow other related articles on the PHP Chinese website!