📖 Scenario: You are building a simple PHP program that processes a list of numbers. You want to apply different operations to each number using functions that you can pass around easily.
🎯 Goal: Learn how to create and use closures (anonymous functions) as callbacks in PHP to process an array of numbers.
📋 What You'll Learn
Create an array of numbers
Create a closure (anonymous function) to double a number
Use the closure as a callback to process the array
Print the processed array
💡 Why This Matters
🌍 Real World
Closures as callbacks are useful when you want to pass small pieces of code to functions for flexible processing, like transforming data or filtering lists.
💼 Career
Understanding closures and callbacks is important for PHP developers working with array functions, event handlers, or asynchronous code.
Progress0 / 4 steps
1
Create the numbers array
Create an array called numbers with these exact values: 1, 2, 3, 4, 5.
PHP
Hint
Use square brackets [] to create an array in PHP.
2
Create a closure to double a number
Create a closure called double that takes one parameter $n and returns $n * 2.
PHP
Hint
Use function($n) { return $n * 2; }; to create the closure.
3
Use the closure as a callback to process the array
Use the array_map function with the double closure to create a new array called doubledNumbers.
PHP
Hint
Use array_map($double, $numbers) to apply the closure to each element.
4
Print the processed array
Print the doubledNumbers array using print_r.
PHP
Hint
Use print_r($doubledNumbers); to display the array.
Practice
(1/5)
1. What is a closure in PHP when used as a callback?
easy
A. A special variable type for storing data
B. A named function that cannot access outside variables
C. An anonymous function that can be passed as an argument
D. A PHP keyword for ending loops
Solution
Step 1: Understand what a closure is
A closure is an anonymous function, meaning it has no name and can be created on the fly.
Step 2: Recognize closures as callbacks
Closures can be passed as arguments to other functions to customize behavior, making them useful as callbacks.
Final Answer:
An anonymous function that can be passed as an argument -> Option C
Quick Check:
Closure = anonymous function callback [OK]
Hint: Closures are nameless functions passed as arguments [OK]
Common Mistakes:
Thinking closures must have names
Confusing closures with variables
Believing closures cannot be passed as arguments
2. Which of the following is the correct syntax to define a closure as a callback in PHP?