Metodo __call
Il metodo __call è un metodo magico in PHP che viene chiamato automaticamente quando si tenta di accedere a un metodo inesistente o inaccessibile di una classe. Accetta come primo parametro il nome del metodo chiamato e come secondo un array di argomenti.
Sintassi
public function __call(string $name, array $arguments) {
// implementazione
}
Esempio
Creiamo una classe con il metodo __call che intercetterà tutte le chiamate ai metodi inesistenti:
<?php
class Test {
public function __call($name, $args) {
echo "Metodo chiamato: " . $name . "\n";
echo "Argomenti: ";
print_r($args);
}
}
$test = new Test();
$test->nonExistentMethod('a', 'b', 123);
?>
Risultato dell'esecuzione del codice:
Metodo chiamato: nonExistentMethod
Argomenti: ['a', 'b', 123]
Esempio
Implementiamo un semplice delegatore di metodi utilizzando __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);
?>
Risultato dell'esecuzione del codice:
5
Vedi anche
-
metodo
__callStatic,
che intercetta le chiamate ai metodi statici -
metodo
__get,
che intercetta gli accessi alle proprietà inesistenti