0
0
PHPprogramming~20 mins

Anonymous function syntax in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Anonymous Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of an anonymous function assigned to a variable
What is the output of this PHP code?
PHP
<?php
$greet = function($name) {
    return "Hello, $name!";
};
echo $greet("Alice");
?>
AError: Undefined variable $name
BHello, $name!
CHello, Alice!
DHello, !
Attempts:
2 left
💡 Hint
Look at how the anonymous function uses the parameter inside the string.
Predict Output
intermediate
2:00remaining
Using 'use' keyword to access external variable
What will this PHP code output?
PHP
<?php
$message = "Hi";
$func = function($name) use ($message) {
    return "$message, $name!";
};
echo $func("Bob");
?>
AHi, $name!
BHi, Bob!
CError: Undefined variable $message
DHi!
Attempts:
2 left
💡 Hint
Check how the 'use' keyword brings $message inside the function.
🔧 Debug
advanced
2:00remaining
Identify the error in anonymous function syntax
What error does this PHP code produce?
PHP
<?php
$func = function($x) {
    return $x * 2
};
echo $func(5);
?>
AParse error: syntax error, unexpected '}', expecting ';'
BFatal error: Call to undefined function function()
CWarning: Missing argument for function
DNo error, outputs 10
Attempts:
2 left
💡 Hint
Check the line before the closing brace for missing punctuation.
Predict Output
advanced
2:00remaining
Anonymous function modifying external variable by reference
What is the output of this PHP code?
PHP
<?php
$count = 0;
$increment = function() use (&$count) {
    $count++;
};
$increment();
$increment();
echo $count;
?>
A0
BError: Cannot use variable by reference
C1
D2
Attempts:
2 left
💡 Hint
Look at how the variable is passed by reference with &.
🧠 Conceptual
expert
3:00remaining
Understanding closure binding in anonymous functions
Given this PHP code, what will be the output?
PHP
<?php
class Counter {
    private int $count = 0;
    public function getIncrementer() {
        return function() {
            $this->count++;
            return $this->count;
        };
    }
}

$counter = new Counter();
$inc = $counter->getIncrementer();
echo $inc();
echo $inc();
?>
A12
B01
CError: Using $this in anonymous function without binding
D11
Attempts:
2 left
💡 Hint
Anonymous functions inside classes can access $this if called correctly.