Challenge - 5 Problems
Anonymous Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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"); ?>
Attempts:
2 left
💡 Hint
Look at how the anonymous function uses the parameter inside the string.
✗ Incorrect
The anonymous function takes a parameter $name and returns a greeting string with that name. When called with "Alice", it outputs "Hello, Alice!".
❓ Predict Output
intermediate2: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"); ?>
Attempts:
2 left
💡 Hint
Check how the 'use' keyword brings $message inside the function.
✗ Incorrect
The 'use' keyword imports the external variable $message into the anonymous function's scope. So it outputs "Hi, Bob!".
🔧 Debug
advanced2: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); ?>
Attempts:
2 left
💡 Hint
Check the line before the closing brace for missing punctuation.
✗ Incorrect
The function body is missing a semicolon after 'return $x * 2'. This causes a syntax error before the closing brace.
❓ Predict Output
advanced2: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; ?>
Attempts:
2 left
💡 Hint
Look at how the variable is passed by reference with &.
✗ Incorrect
The anonymous function uses &$count to modify the external variable directly. Calling it twice increments count to 2.
🧠 Conceptual
expert3: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(); ?>
Attempts:
2 left
💡 Hint
Anonymous functions inside classes can access $this if called correctly.
✗ Incorrect
The anonymous function is a closure that inherits $this from the Counter object. Each call increments $this->count and returns the new value, so it outputs 1 followed by 2, resulting in "12".