The __call Method
The __call
method is a magic method in PHP that is automatically called when attempting to access a non-existent or inaccessible class method. It accepts the name of the called method as the first parameter, and an array of arguments as the second.
Syntax
public function __call(string $name, array $arguments) {
// implementation
}
Example
Let's create a class with the __call
method that will intercept all calls to non-existent methods:
<?php
class Test {
public function __call($name, $args) {
echo "Called method: " . $name . "\n";
echo "Arguments: ";
print_r($args);
}
}
$test = new Test();
$test->nonExistentMethod('a', 'b', 123);
?>
Execution result:
Called method: nonExistentMethod
Arguments: ['a', 'b', 123]
Example
Let's implement a simple method delegator using __call
:
<?php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
}
class Math {
private $calculator;
public function __construct() {
$this->calculator = new Calculator();
}
public function __call($name, $args) {
if (method_exists($this->calculator, $name)) {
return call_user_func_array(
[$this->calculator, $name],
$args
);
}
throw new Exception("Method $name not found");
}
}
$math = new Math();
echo $math->add(2, 3);
?>
Execution result:
5
See Also
-
the
__callStatic
method,
which intercepts static method calls -
the
__get
method,
which intercepts access to non-existent properties