0
0
PHPprogramming~20 mins

Closures and variable binding with use in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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();
A10
B0
C20
DError: Undefined variable
Attempts:
2 left
💡 Hint
Remember that variables passed with use are copied by value unless passed by reference.
Predict Output
intermediate
2: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;
A5 15
BError: Cannot use variable by reference
C15 5
D15 15
Attempts:
2 left
💡 Hint
Binding by reference means changes inside the closure affect the original variable.
🔧 Debug
advanced
2: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;
ABecause $count is not initialized before use.
BBecause $count is passed by value, so increment inside closure doesn't affect outside variable.
CBecause closures cannot modify variables from outer scope.
DBecause $count is passed by reference but not incremented properly.
Attempts:
2 left
💡 Hint
Think about how variables are passed into closures with use().
Predict Output
advanced
2: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();
A1 2 2
B2 3 3
C1 3 3
D2 2 2
Attempts:
2 left
💡 Hint
Remember that $a is passed by value and $b by reference in inner closure.
🧠 Conceptual
expert
3: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?
ABecause the closure holds a reference to the original variable, so changes outside affect closure behavior dynamically.
BBecause PHP copies the variable value at closure creation, so changes outside do not affect closure.
CBecause closures cannot access variables by reference in PHP.
DBecause binding by reference causes a syntax error if variable changes later.
Attempts:
2 left
💡 Hint
Think about how references work in PHP and how closures keep references.