Home >Database >Mysql Tutorial >PHP closure instance analysis
Anonymous functions (Anonymous functions), also called closure functions, allow temporarily creating a function without a specified name. The value most often used as the callback function (callback) parameter. Of course, there are other applications as well.
Anonymous functions are currently implemented through the Closure class.
Closure functions can also be used as the value of variables. PHP will automatically convert this expression into an object instance of the built-in class Closure. The method of assigning a closure object to a variable is the same as the syntax of ordinary variable assignment, and a semicolon must be added at the end:
Closures can be accessed from the parent scope Medium inherits variables. Any such variables should be passed in using the use language construct. Starting from PHP 7.1, such variables cannot be passed in: superglobals, $this or have the same name as parameters.
The specific form is as follows:
$a = function($arg1, $arg2) use ($variable) { // 声明函数闭包到变量$a, 参数为$arg1, $arg2 ,该闭包需使用$variable变量 }
The specific usage examples are as follows:
<?php $result = 0; $one = function() { var_dump($result); }; $two = function() use ($result) { var_dump($result); }; // 可以认为 $two这个变量 本身记录了该函数的声明以及use使用的变量的值 $three = function() use (&$result) { var_dump($result); }; $result++; $one(); // outputs NULL: $result is not in scope $two(); // outputs int(0): $result was copied $three(); // outputs int(1) ?>
The above is the detailed content of PHP closure instance analysis. For more information, please follow other related articles on the PHP Chinese website!