Master PHP Closures: Build Flexible Functions with Anonymous Functions
This article explains PHP closures—anonymous functions that enable dynamic, reusable code—by covering their basic syntax, how to pass them as parameters, and how to generate variable functions at runtime, complete with clear code examples and practical explanations.
1. Closure Basics
In PHP a closure (anonymous function) is defined with the function() {} syntax; it can accept parameters and return a value. Example:
$add = function($a, $b) {
return $a + $b;
};
$result = $add(2, 3); // outputs 5
echo $result;The variables $a and $b are the parameters, and the result is stored in $result.
2. Using Closures as Function Parameters
A closure can be passed to another function, allowing dynamic behavior at runtime. Example:
function calculate($a, $b, $operation) {
return $operation($a, $b);
}
$add = function($a, $b) {
return $a + $b;
};
$result = calculate(2, 3, $add); // outputs 5
echo $result;The calculate function receives a closure $operation and invokes it without needing to change its own code.
3. Creating Variable Functions with Closures
Closures can be returned from a factory function to produce different operations based on a parameter. Example:
function getOperation($operator) {
if ($operator === '+') {
return function($a, $b) { return $a + $b; };
} elseif ($operator === '-') {
return function($a, $b) { return $a - $b; };
} elseif ($operator === '*') {
return function($a, $b) { return $a * $b; };
}
}
$operator = '*';
$operation = getOperation($operator);
$result = $operation(2, 3); // outputs 6
echo $result;The getOperation function returns a closure matching the requested operator, enabling flexible, condition‑based function generation.
Overall, PHP closures provide a powerful, flexible way to create reusable functions, pass behavior as arguments, and generate functions dynamically, improving code readability and maintainability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
