Complete the code to make the object callable using __invoke.
<?php class CallableClass { public function [1]() { echo "Called!"; } } $obj = new CallableClass(); $obj(); ?>
The __invoke method allows an object to be called like a function.
Complete the code to return a string when the object is called.
<?php class Greeter { public function [1]() { return "Hello!"; } } $greet = new Greeter(); echo $greet(); ?>
The __invoke method can return values when the object is called like a function.
Fix the error in the code to make the object callable.
<?php class Counter { private $count = 0; public function [1]() { $this->count++; return $this->count; } } $c = new Counter(); echo $c(); ?>
The __invoke method must be defined to allow the object to be called like a function.
Fill both blanks to create a callable object that multiplies a number by a factor.
<?php class Multiplier { private $factor; public function __construct($factor) { $this->factor = [1]; } public function [2]($number) { return $number * $this->factor; } } $mul = new Multiplier(5); echo $mul(3); ?>
Use $factor to assign the constructor argument, and __invoke to make the object callable.
Fill all three blanks to create a callable object that stores and returns a message.
<?php class Messenger { private $message; public function __construct([1]) { $this->message = [2]; } public function [3]() { return $this->message; } } $msg = new Messenger("Hi there!"); echo $msg(); ?>
The constructor takes $message as argument and assigns it to $this->message. The __invoke method returns the message when the object is called.