Recall & Review
beginner
What is a closure in PHP?
A closure is an anonymous function that can capture variables from its surrounding scope and be used as a callback or stored in a variable.
Click to reveal answer
beginner
How do you define a closure to use as a callback in PHP?
You define an anonymous function using the
function keyword without a name, optionally capturing variables with use, and pass it as an argument where a callback is expected.Click to reveal answer
intermediate
What does the
use keyword do in a PHP closure?The
use keyword allows a closure to access variables from the parent scope by copying them into the closure's scope.Click to reveal answer
intermediate
Why are closures useful as callbacks?
Closures let you write small, inline functions that can access variables from outside their scope, making callbacks flexible and easy to customize without defining a full named function.Click to reveal answer
beginner
Example: What will this PHP code output?
$greet = function($name) { return "Hello, $name!"; };
echo $greet('Alice');It will output:
Hello, Alice! because the closure takes the argument $name and returns a greeting string.Click to reveal answer
What keyword is used to create an anonymous function (closure) in PHP?
✗ Incorrect
In PHP, the
function keyword is used to create anonymous functions, which are closures.How do you access a variable from the parent scope inside a closure?
✗ Incorrect
The
use keyword imports variables from the parent scope into the closure.Which of these is a valid way to pass a closure as a callback in PHP?
✗ Incorrect
You can pass an anonymous function directly as a callback, like in option D.
What will this code output?
$factor = 3;
$multiply = function($n) use ($factor) { return $n * $factor; };
echo $multiply(5);✗ Incorrect
The closure uses the
$factor variable from the parent scope and multiplies 5 by 3, outputting 15.Why might you prefer a closure over a named function for a callback?
✗ Incorrect
Closures are convenient for quick, inline callbacks and can capture variables from their surrounding scope.
Explain how closures work as callbacks in PHP and how they can access variables from outside their scope.
Think about how you write a small function inside another function and still use outside data.
You got /4 concepts.
Describe a simple example of using a closure as a callback with array_map in PHP.
Imagine you want to double every number in a list using a small function.
You got /4 concepts.