0
0
PHPprogramming~5 mins

__call and __callStatic in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the __call magic method in PHP?

The __call method is triggered when invoking inaccessible or undefined instance methods on an object. It allows handling or customizing calls to methods that do not exist.

Click to reveal answer
beginner
How does __callStatic differ from __call in PHP?

__callStatic is triggered when calling inaccessible or undefined static methods, while __call handles instance method calls.

Click to reveal answer
beginner
What are the two parameters passed to __call and __callStatic methods?

Both methods receive:<br>1. $name: The name of the method being called.<br>2. $arguments: An array of arguments passed to the method.

Click to reveal answer
intermediate
Can __call and __callStatic be used to create flexible APIs or method overloading in PHP?

Yes, they allow intercepting calls to undefined methods, enabling dynamic method handling and simulating method overloading behavior.

Click to reveal answer
beginner
Provide a simple example of using __call in a PHP class.
<pre>&lt;?php
class Example {
    public function __call($name, $arguments) {
        return "Called method '$name' with arguments: " . implode(', ', $arguments);
    }
}

$obj = new Example();
echo $obj->testMethod('hello', 'world');
// Output: Called method 'testMethod' with arguments: hello, world
?&gt;</pre>
Click to reveal answer
Which magic method is called when an undefined instance method is invoked in PHP?
A__call
B__callStatic
C__invoke
D__get
What parameters do __call and __callStatic receive?
AOnly method name
BOnly arguments array
CMethod name and arguments array
DNo parameters
Which magic method is triggered by calling an undefined static method?
A__callStatic
B__call
C__set
D__get
Can __call be used to simulate method overloading in PHP?
ANo
BYes
COnly with static methods
DOnly in PHP 8+
What will happen if you call an undefined instance method and __call is not defined?
AIgnores the call
BReturns null
CCalls <code>__callStatic</code>
DFatal error
Explain how __call and __callStatic work in PHP and when they are triggered.
Think about instance vs static method calls.
You got /4 concepts.
    Describe a practical use case where __call or __callStatic can be helpful.
    Consider situations where method names are not fixed.
    You got /4 concepts.