0
0
PHPprogramming~20 mins

__invoke for callable objects in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Invoke Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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");
ANothing is printed
BFatal error: Uncaught Error: Call to undefined method Greeter::__invoke()
CHello, World!
DHello, Alice!
Attempts:
2 left
💡 Hint
Remember that __invoke allows an object to be called like a function.
🧠 Conceptual
intermediate
1:30remaining
Purpose of __invoke in PHP
What is the main purpose of the __invoke magic method in PHP?
ATo allow an object to be called as if it were a function
BTo automatically convert an object to a string
CTo initialize object properties when created
DTo overload arithmetic operators for objects
Attempts:
2 left
💡 Hint
Think about how you can use an object like a function.
Predict Output
advanced
2: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);
A12
B7
CFatal error: Too few arguments to function Calculator::__invoke()
D0
Attempts:
2 left
💡 Hint
Check how the __invoke method uses the two parameters.
🔧 Debug
advanced
2: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();
ANothing is printed
BFatal error: Uncaught Error: Call to undefined method Printer::__invoke()
CPrinting message
DParse error: syntax error, unexpected '()'
Attempts:
2 left
💡 Hint
Check if the class has __invoke defined.
🚀 Application
expert
3: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);
ADoubler::__invoke
B"Doubler"
Cnew Doubler()
D[Doubler, '__invoke']
Attempts:
2 left
💡 Hint
array_map expects a callable. An object with __invoke is callable.