These special methods let a PHP class handle calls to methods that don't exist. It helps catch mistakes or add flexible behavior.
0
0
__call and __callStatic in PHP
Introduction
You want to handle calls to methods that are not defined in your class.
You want to create flexible classes that can respond to many method names dynamically.
You want to log or debug when someone tries to call a missing method.
You want to create proxy or wrapper classes that forward calls to other objects.
You want to provide default behavior for undefined static or instance methods.
Syntax
PHP
public function __call(string $name, array $arguments) { // code to handle instance method calls } public static function __callStatic(string $name, array $arguments) { // code to handle static method calls }
__call handles calls to missing instance methods.
__callStatic handles calls to missing static methods.
Examples
This shows
__call catching a call to a missing instance method hello.PHP
<?php class Example { public function __call($name, $arguments) { echo "Called instance method '$name' with arguments: " . implode(', ', $arguments) . "\n"; } } $obj = new Example(); $obj->hello('world');
This shows
__callStatic catching a call to a missing static method greet.PHP
<?php class Example { public static function __callStatic($name, $arguments) { echo "Called static method '$name' with arguments: " . implode(', ', $arguments) . "\n"; } } Example::greet('everyone');
Sample Program
This program shows both __call and __callStatic in action. When calling missing instance method foo, __call runs. When calling missing static method bar, __callStatic runs.
PHP
<?php class Magic { public function __call($name, $arguments) { echo "Instance method '$name' called with arguments: " . implode(', ', $arguments) . "\n"; } public static function __callStatic($name, $arguments) { echo "Static method '$name' called with arguments: " . implode(', ', $arguments) . "\n"; } } $obj = new Magic(); $obj->foo('apple', 'banana'); Magic::bar('carrot');
OutputSuccess
Important Notes
These methods only run when the called method does not exist or is inaccessible.
Use __call for instance methods and __callStatic for static methods.
Arguments are passed as an array, so you can handle any number of parameters.
Summary
__call handles missing instance method calls.
__callStatic handles missing static method calls.
They help make classes flexible and catch unexpected method calls.