Backend Development 2 min read

Using Anonymous Functions (Closures) in PHP: Examples and Techniques

This article explains PHP anonymous functions (closures), demonstrating how to reference local variables with the use keyword, embed anonymous functions within regular functions, return them, pass parameters, and use them as arguments, accompanied by clear code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using Anonymous Functions (Closures) in PHP: Examples and Techniques

In PHP, anonymous functions (also called closures ) allow you to define a function without a name, and they are most commonly used as callback parameters.

1. Referencing local variables inside an anonymous function (using the use keyword).

<?php
function F1(){
    $ok = "HelloWorld";
    $a = function() use ($ok) {
        echo "$ok";
    };
    $a();
}
F1();
?>

2. Placing an anonymous function inside a regular function.

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

3. Returning an anonymous function from a regular function.

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

4. Returning an anonymous function and passing parameters to it.

<?php
function F1(){
    $a = function($name, $do) {
        echo $name . " " . $do . " HelloWorld";
    };
    return $a;
}
$abc = F1();
$abc('张三', 'say');
?>

5. Using an anonymous function as a parameter to another function.

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

F1(function ($username){
    echo $username;
});
?>
backend developmentCallbacksClosuresAnonymous Functions
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.