Challenge - 5 Problems
Invoke Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of __invoke method call
What is the output of this PHP code when the object is called as a function?
PHP
<?php class Greeter { public function __invoke(string $name): string { return "Hello, $name!"; } } $greet = new Greeter(); echo $greet("Alice");
Attempts:
2 left
💡 Hint
Remember that __invoke allows an object to be called like a function.
✗ Incorrect
The __invoke method is called when an object is used as a function. Here, calling $greet('Alice') triggers __invoke with 'Alice' as argument, returning 'Hello, Alice!'.
🧠 Conceptual
intermediate1:30remaining
Purpose of __invoke in PHP
What is the main purpose of the __invoke magic method in PHP?
Attempts:
2 left
💡 Hint
Think about how you can use an object like a function.
✗ Incorrect
The __invoke method lets you call an object like a function, executing the code inside __invoke when you do so.
❓ Predict Output
advanced2:00remaining
Output with multiple __invoke parameters
What will this PHP code output?
PHP
<?php class Calculator { public function __invoke(int $a, int $b): int { return $a * $b; } } $calc = new Calculator(); echo $calc(3, 4);
Attempts:
2 left
💡 Hint
Check how the __invoke method uses the two parameters.
✗ Incorrect
The __invoke method multiplies the two arguments 3 and 4, returning 12.
🔧 Debug
advanced2:00remaining
Identify the error when calling an object without __invoke
What error will this PHP code produce?
PHP
<?php class Printer { public function printMessage() { echo "Printing message"; } } $p = new Printer(); echo $p();
Attempts:
2 left
💡 Hint
Check if the class has __invoke defined.
✗ Incorrect
Since Printer does not have __invoke, calling $p() causes a fatal error about undefined method __invoke.
🚀 Application
expert3:00remaining
Using __invoke for a callable class in a callback
Which option correctly uses a class with __invoke as a callback for array_map to double each number?
PHP
<?php class Doubler { public function __invoke(int $n): int { return $n * 2; } } $numbers = [1, 2, 3, 4]; $result = array_map( /* fill here */, $numbers); print_r($result);
Attempts:
2 left
💡 Hint
array_map expects a callable. An object with __invoke is callable.
✗ Incorrect
Passing an instance of Doubler works because __invoke makes the object callable. The other options are invalid or cause errors.