0
0
PHPprogramming~10 mins

__invoke for callable objects in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the object callable using __invoke.

PHP
<?php
class CallableClass {
    public function [1]() {
        echo "Called!";
    }
}
$obj = new CallableClass();
$obj();
?>
Drag options to blanks, or click blank then click option'
A__invoke
B__toString
C__construct
D__call
Attempts:
3 left
💡 Hint
Common Mistakes
Using __call instead of __invoke
Forgetting to define __invoke method
Trying to call the object without __invoke defined
2fill in blank
medium

Complete the code to return a string when the object is called.

PHP
<?php
class Greeter {
    public function [1]() {
        return "Hello!";
    }
}
$greet = new Greeter();
echo $greet();
?>
Drag options to blanks, or click blank then click option'
A__toString
B__destruct
C__callStatic
D__invoke
Attempts:
3 left
💡 Hint
Common Mistakes
Using __toString which is for string conversion
Trying to call the object without __invoke defined
3fill in blank
hard

Fix the error in the code to make the object callable.

PHP
<?php
class Counter {
    private $count = 0;
    public function [1]() {
        $this->count++;
        return $this->count;
    }
}
$c = new Counter();
echo $c();
?>
Drag options to blanks, or click blank then click option'
A__get
B__call
C__invoke
D__set
Attempts:
3 left
💡 Hint
Common Mistakes
Using __call which is for undefined method calls
Not defining __invoke method
4fill in blank
hard

Fill both blanks to create a callable object that multiplies a number by a factor.

PHP
<?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);
?>
Drag options to blanks, or click blank then click option'
A$factor
B__call
C__invoke
D$this->factor
Attempts:
3 left
💡 Hint
Common Mistakes
Using __call instead of __invoke
Assigning wrong variable in constructor
5fill in blank
hard

Fill all three blanks to create a callable object that stores and returns a message.

PHP
<?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();
?>
Drag options to blanks, or click blank then click option'
A$msg
B$message
C__invoke
D$this->message
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names in constructor
Not defining __invoke method