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;
});
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CallbacksclosuresAnonymous 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

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.