Challenge - 5 Problems
Closure Master in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a closure capturing a variable
What is the output of this PHP code that uses a closure capturing a variable by reference?
PHP
<?php $counter = 0; $increment = function() use (&$counter) { $counter++; return $counter; }; echo $increment(); echo $increment(); ?>
Attempts:
2 left
💡 Hint
Closures can capture variables by reference, so changes inside affect the original variable.
✗ Incorrect
The closure captures $counter by reference, so each call increments the same variable. The first call returns 1, the second returns 2, so output is '12'.
🧠 Conceptual
intermediate1:30remaining
Why use closures in PHP?
Which of the following best explains why closures matter in PHP?
Attempts:
2 left
💡 Hint
Think about how closures keep variables alive beyond their normal lifetime.
✗ Incorrect
Closures capture variables from their surrounding scope, allowing the function to use those variables even after the outer function has finished.
🔧 Debug
advanced2:30remaining
Identify the error with closure variable capture
What error will this PHP code produce and why?
PHP
<?php $funcs = []; for ($i = 0; $i < 3; $i++) { $funcs[] = function() { return $i; }; } foreach ($funcs as $f) { echo $f(); } ?>
Attempts:
2 left
💡 Hint
Variables inside closures must be explicitly captured with use().
✗ Incorrect
The closure does not capture $i, so it uses the variable from the outer scope at the time of execution, which is 3 after the loop ends. So it outputs '333'.
📝 Syntax
advanced1:30remaining
Correct syntax for closure with parameters
Which option shows the correct syntax for a PHP closure that takes one parameter and returns its square?
Attempts:
2 left
💡 Hint
Closures use the function keyword followed by parentheses for parameters.
✗ Incorrect
Option A correctly defines a closure with one parameter $x and returns its square. Option A misses parentheses, C uses invalid arrow syntax, D is invalid syntax.
🚀 Application
expert3:00remaining
Using closures to create a counter generator
Which option correctly creates a closure in PHP that returns a function acting as a counter starting from 0 and increasing by 1 each call?
Attempts:
2 left
💡 Hint
To keep the count variable updated across calls, capture it by reference.
✗ Incorrect
Option C captures $count by reference, so each call increments the same variable. Option C fails because static $count is not in closure scope. Option C does not capture $count, so it resets each call. Option C captures by value, so increments do not persist.