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.
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;
});
?>php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.