PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
13: Anonymous Functions and Closures
Up until now, every function we've written has had a name. That's great for things you use everywhere, but sometimes you just need a bit of logic for a one-off task—like filtering a list or sorting a weirdly structured array. In those cases, naming a function feels like overkill. That's where anonymous functions (and their more powerful cousins, closures) come in.
Creating a quick filter on the fly
Let's say we're building a simple product catalog. We have an array of products, and we want to filter them. Instead of writing five different functions for "cheap products," "expensive products," and "out of stock products," I'm going to write one generic filter function that accepts another function as an argument. This is a common pattern in functional programming.
$products = [
['name' => 'Mechanical Keyboard', 'price' => 120, 'stock' => 5],
['name' => 'Gaming Mouse', 'price' => 60, 'stock' => 0],
['name' => 'UltraWide Monitor', 'price' => 450, 'stock' => 2],
['name' => 'USB-C Cable', 'price' => 15, 'stock' => 20],
];
function filterProducts(array $products, callable $callback) {
$filtered = [];
foreach ($products as $product) {
if ($callback($product)) {
$filtered[] = $product;
}
}
return $filtered;
}
// Here's the anonymous function. No name, just logic.
$cheapProducts = filterProducts($products, function($product) {
return $product['price'] < 100;
});
print_r($cheapProducts);
See what happened there? I passed a function directly into filterProducts. I didn't have to define a global isCheap() function that I'll never use again. It's clean and keeps the logic right where it's being used.
Where I usually trip up: Scope
Now, let's make it more dynamic. I want to let the user decide the price threshold. I'll define a variable $maxPrice and try to use it inside my anonymous function. I'll write this the way I did the first time I learned PHP, which is the wrong way.
$maxPrice = 50;
$budgetProducts = filterProducts($products, function($product) {
// I'm assuming $maxPrice is available here because it's in the outer scope.
return $product['price'] < $maxPrice;
});
print_r($budgetProducts);
If you run this, you'll notice it returns an empty array or throws a warning. Why? Because in PHP, anonymous functions don't automatically inherit variables from the parent scope. They are isolated. I just tried to access $maxPrice, but the function has no idea what that is. It's a classic "gotcha" that has cost me plenty of debugging hours over the years.
Closing the gap with the 'use' keyword
To fix this, we turn the anonymous function into a closure. A closure "closes over" the variables it needs from the outside world. In PHP, we do this explicitly using the use keyword in the function signature.
$maxPrice = 50;
// We explicitly tell PHP to bring $maxPrice into the function's scope
$budgetProducts = filterProducts($products, function($product) use ($maxPrice) {
return $product['price'] < $maxPrice;
});
print_r($budgetProducts);
Now it works. By adding use ($maxPrice), I've effectively captured that variable at the moment the function was created. One thing to keep in mind: the variable is captured by value by default. If you change $maxPrice after the closure is defined, the closure will still use the value it had when it was first created. If you need it to stay synced, you'd pass it by reference using use (&$maxPrice), but you'll rarely need to do that for simple filtering.
📋 Practical Task
Building a Dynamic Tax Calculator
You are building a checkout system where different states have different tax rates. Instead of writing a separate function for every state, you will use a closure to create a flexible tax applicator.
Your Task:
- Create an array of order totals (e.g.,
[100, 250, 40, 10]). - Define a variable
$taxRate(e.g.,0.07for 7%). - Write a function called
applyTaxthat takes an array of amounts and acallable. TheapplyTaxfunction should return a new array where the callback has been applied to every amount. - Call
applyTaxusing an anonymous function that uses theusekeyword to bring in the$taxRateand calculate the total (Amount + (Amount * TaxRate)). - Print the resulting array of taxed totals to the screen.
There are no comments for now.