Challenge - 5 Problems
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of closure with variable binding by value
What is the output of this PHP code?
PHP
<?php $number = 10; $func = function() use ($number) { echo $number; }; $number = 20; $func();
Attempts:
2 left
💡 Hint
Remember that variables passed with use are copied by value unless passed by reference.
✗ Incorrect
The closure captures $number by value at the time of definition, so it prints 10 even though $number changes later.
❓ Predict Output
intermediate2:00remaining
Output of closure with variable binding by reference
What will this PHP code output?
PHP
<?php $value = 5; $func = function() use (&$value) { $value += 10; echo $value; }; $func(); echo ' ' . $value;
Attempts:
2 left
💡 Hint
Binding by reference means changes inside the closure affect the original variable.
✗ Incorrect
The closure modifies $value by adding 10. Since it is bound by reference, both echo statements print 15.
🔧 Debug
advanced2:30remaining
Why does this closure not update the variable?
Consider this PHP code snippet. Why does the variable $count not increment outside the closure?
PHP
<?php $count = 0; $increment = function() use ($count) { $count++; }; $increment(); echo $count;
Attempts:
2 left
💡 Hint
Think about how variables are passed into closures with use().
✗ Incorrect
The closure captures $count by value, so incrementing it inside does not change the original $count outside.
❓ Predict Output
advanced2:30remaining
Output of nested closures with variable binding
What is the output of this PHP code?
PHP
<?php $a = 1; $outer = function() use ($a) { $b = 2; $inner = function() use ($a, &$b) { $a++; $b++; echo $a . ' ' . $b; }; $inner(); echo ' ' . $b; }; $outer();
Attempts:
2 left
💡 Hint
Remember that $a is passed by value and $b by reference in inner closure.
✗ Incorrect
Inside inner closure, $a++ affects only local copy (1->2 but not reflected outside), $b++ affects original $b (2->3). So echo prints '2 3' and then outer echo prints ' 3'.
🧠 Conceptual
expert3:00remaining
Why does binding by reference in closure cause unexpected behavior?
In PHP, binding a variable by reference in a closure can sometimes cause unexpected results when the variable changes after closure creation. Why does this happen?
Attempts:
2 left
💡 Hint
Think about how references work in PHP and how closures keep references.
✗ Incorrect
Binding by reference means the closure uses the original variable's memory. If the variable changes outside, the closure sees the updated value, which can cause unexpected dynamic behavior.