0
0
PHPprogramming~10 mins

Why magic methods exist in PHP - Test Your Understanding

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

Complete the code to define a magic method that is called when an undefined property is accessed.

PHP
<?php
class Test {
    public function [1]($name) {
        return "Property $name does not exist.";
    }
}
$test = new Test();
echo $test->foo;
?>
Drag options to blanks, or click blank then click option'
A__set
B__get
C__call
D__construct
Attempts:
3 left
💡 Hint
Common Mistakes
Using __set instead of __get
Using __call which is for methods
Using __construct which is the constructor
2fill in blank
medium

Complete the code to define a magic method that is called when an undefined method is called.

PHP
<?php
class Test {
    public function [1]($name, $arguments) {
        return "Method $name does not exist.";
    }
}
$test = new Test();
echo $test->foo();
?>
Drag options to blanks, or click blank then click option'
A__call
B__get
C__set
D__invoke
Attempts:
3 left
💡 Hint
Common Mistakes
Using __get which is for properties
Using __set which is for setting properties
Using __invoke which is for calling objects as functions
3fill in blank
hard

Fix the error in the magic method that sets a property value.

PHP
<?php
class Test {
    public function [1]($name, $value) {
        $this->$name = $value;
    }
}
$test = new Test();
$test->foo = 'bar';
echo $test->foo;
?>
Drag options to blanks, or click blank then click option'
A__get
B__construct
C__call
D__set
Attempts:
3 left
💡 Hint
Common Mistakes
Using __get instead of __set
Using __call which is for methods
Using __construct which is the constructor
4fill in blank
hard

Fill both blanks to create a magic method that returns a string when the object is treated as a string.

PHP
<?php
class Test {
    public function [1]() {
        return [2];
    }
}
$test = new Test();
echo $test;
?>
Drag options to blanks, or click blank then click option'
A__toString
B__invoke
C"This is a Test object."
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using __invoke which is for calling objects as functions
Not returning a string
Using return keyword as method name
5fill in blank
hard

Fill all three blanks to create a magic method that is called when the object is used as a function.

PHP
<?php
class Test {
    public function [1]([2]) {
        return "Called with argument: " . [3];
    }
}
$test = new Test();
echo $test('hello');
?>
Drag options to blanks, or click blank then click option'
A__invoke
B$arg
D__call
Attempts:
3 left
💡 Hint
Common Mistakes
Using __call which is for undefined methods
Not using the argument variable
Using wrong method name