Home >Backend Development >PHP Tutorial >Tips for using anonymous functions in PHP

Tips for using anonymous functions in PHP

autoload
autoloadOriginal
2021-04-02 10:33:332457browse

<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(&#39;张三&#39;,&#39;say&#39;);
?>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn