Home >Backend Development >PHP Tutorial >Tips for using anonymous functions in PHP
<img src="https://img.php.cn/upload/image/467/414/724/1617330675913128.jpg" title="1617330675913128.jpg" alt="Tips for using anonymous functions in PHP">
Anonymous functions
(Anonymous functions) in PHP
are also called closure functions
(closures), allows specifying a function without a name. The most commonly used one is the parameter value of callback function
.
1. Reference local variables in anonymous functions (use the use keyword in PHP here).
<?php function F1(){ $ok="HelloWorld"; $a=function() use($ok) { echo "$ok"; }; $a(); } F1(); ?>
2. Place the anonymous function in a normal function, or return the anonymous function.
<?php function F1(){ $a=function() { echo "HelloWorld"; }; $a(); } F1(); ?>
3. Return in an ordinary function.
<?php function F1(){ $a=function() { echo "HelloWorld"; }; return $a; } $abc=F1(); $abc(); ?>
4. Return the anonymous function and pass parameters to the anonymous function.
<?php function F1(){ $a=function($name,$do) { echo $name." ".$do." HelloWorld"; }; return $a; } $abc=F1(); $abc('张三','say'); ?>
5. Pass anonymous functions as parameters.
<?php function F1($UnkownFun){ $UnkownFun("张三"); } F1(function ($username){ echo $username; }); ?>
Recommended: 《2021 PHP interview questions summary (collection)》《php video tutorial》
The above is the detailed content of Tips for using anonymous functions in PHP. For more information, please follow other related articles on the PHP Chinese website!