Consider the following PHP class with a __call magic method. What will be printed when the code runs?
<?php class Test { public function __call($name, $arguments) { echo "Called method '$name' with arguments: " . implode(", ", $arguments) . "\n"; } } $obj = new Test(); $obj->hello('world', 123); ?>
The __call method catches calls to undefined instance methods and receives the method name and arguments.
The __call magic method is triggered when an undefined instance method is called. It receives the method name as the first argument and an array of arguments as the second. Here, it prints the method name and all arguments in order.
Given this PHP class with a __callStatic method, what will be the output?
<?php class StaticTest { public static function __callStatic($name, $arguments) { echo "Static call to '$name' with args: " . implode(", ", $arguments) . "\n"; } } StaticTest::foo('a', 'b'); ?>
The __callStatic method handles calls to undefined static methods.
The __callStatic magic method is triggered when an undefined static method is called. It receives the method name and arguments. Here, it prints the method name and arguments in order.
Examine this PHP code. Why does it cause a fatal error instead of invoking __callStatic?
<?php class Demo { public function __callStatic($name, $args) { echo "Called static method $name"; } } Demo::test(); ?>
Check the method declaration for __callStatic and whether it is static.
The __callStatic magic method must be declared as static. In this code, it is declared as an instance method, so PHP does not recognize it as the magic static handler, causing a fatal error when calling an undefined static method.
Choose the option that correctly declares both __call and __callStatic magic methods in a PHP class.
Remember that __call is for instance methods and __callStatic is for static methods.
__call must be an instance method (no static keyword) and accept two parameters: method name and arguments array. __callStatic must be static and accept the same parameters. Option B correctly declares both.
Given this PHP class that stores called method names in arrays via __call and __callStatic, how many items are in $obj->calls and Test::$staticCalls after the code runs?
<?php class Test { public $calls = []; public static $staticCalls = []; public function __call($name, $args) { $this->calls[] = $name; } public static function __callStatic($name, $args) { self::$staticCalls[] = $name; } } $obj = new Test(); $obj->foo(); $obj->bar(); Test::baz(); Test::qux(); ?>
Count how many times instance and static undefined methods are called.
The instance calls foo() and bar() trigger __call, adding 2 items to $calls. The static calls baz() and qux() trigger __callStatic, adding 2 items to $staticCalls.