Closure function: Temporarily create a function without a name, often used as a callback function. In layman's terms: child functions can use local variables in the parent function. This behavior is called closure.
Recommended tutorial: PHP video tutorial
1. Anonymous function assignment
$demo=function($str){ echo $str; } $demo('hello,world');
2. Closures can inherit variables from the parent scope. 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();
Result: hello;
$example=function() use (&$message){ var_dump($message); }
Result: hello;
$message='world'; echo $example();
Result: world;
$example=function($arg) use ($message){ var_dump($arg.' '.$message); } $example('hello');
Result: hello world;
The above is the detailed content of What is the closure in php?. For more information, please follow other related articles on the PHP Chinese website!