Functions · Lesson 7 of 9
Anonymous Functions
Create a closure when behavior is useful as a value.
Lesson
An anonymous function has no declared name and can be stored or passed as a callback. A closure captures outside variables explicitly with use; capture by value unless mutation is intentional. Named functions are often clearer for behavior reused in several places.
This closure captures a tax rate and calculates the total for one amount.
Further guidance
Treat a function as a small contract: name its inputs, state what it returns, and avoid hidden dependencies. Test a representative value and an edge case. Keep a function focused; callers should decide how to display a returned result or handle a reported failure.
Practice task: Create a fresh example for Anonymous Functions. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Anonymous Functions
PHP
$rate = 0.1;
$withTax = function (float $amount) use ($rate): float {
return $amount * (1 + $rate);
};
echo $withTax(100);
Expected output
110
Key points
- Create a closure when behavior is useful as a value.
- Keep inputs, return values, and side effects explicit.
- Prefer focused functions that are easy to test independently.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.