Home >Backend Development >PHP Problem >What can PHP anonymous functions be used for?
Anonymous functions, also called closures, allow the temporary creation of a function without a specified name.
Benefits of anonymous functions
1. Non-anonymous functions create function objects and scope objects when they are defined. If they are not called in the future, they also take up space
2. Anonymous functions will only create function objects and scope objects when they are called. Release immediately after calling to save memory.
Use of anonymous functions in php
1. Use it as a callback function
<?php echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 输出 helloWorld
2. Assign a variable value
<?php $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); $greet('PHP');
Output :
3. Inherit variables from the parent scope
<?php $message = 'hello'; // 没有 "use" $example = function () { var_dump($message); }; echo $example(); // 继承 $message $example = function () use ($message) { var_dump($message); }; echo $example();
Output:
The above is the detailed content of What can PHP anonymous functions be used for?. For more information, please follow other related articles on the PHP Chinese website!