Tips for using anonymous functions in PHP

autoload
Release: 2023-04-09 20:42:01
Original
2429 people have browsed it

<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();
?>
Copy after login

2. Place the anonymous function in a normal function, or return the anonymous function.

<?php 
function F1(){
    $a=function() {
        echo "HelloWorld";
    };
    $a();
}
F1();
?>
Copy after login

3. Return in an ordinary function.

<?php 
function F1(){
    $a=function() {
        echo "HelloWorld";
    };
    return $a;
}
$abc=F1();
$abc();
?>
Copy after login

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;);
?>
Copy after login

5. Pass anonymous functions as parameters.

<?php 
function F1($UnkownFun){
    $UnkownFun("张三");
}

F1(function ($username){
      echo $username;
});

?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template