Metod __call
Metod __call je magični metod u PHP-u koji se automatski poziva pri pokušaju pristupa nepostojećem ili nedostupnom metodu klase. Kao prvi parametar prima ime pozvanog metoda, a kao drugi - niz argumenata.
Sintaksa
public function __call(string $name, array $arguments) {
// implementacija
}
Primer
Kreirajmo klasu sa metodom __call koji će presretati sve pozive nepostojećih metoda:
<?php
class Test {
public function __call($name, $args) {
echo "Pozvan metod: " . $name . "\n";
echo "Argumenti: ";
print_r($args);
}
}
$test = new Test();
$test->nonExistentMethod('a', 'b', 123);
?>
Rezultat izvršavanja koda:
Called method: nonExistentMethod
Arguments: ['a', 'b', 123]
Primer
Implementirajmo jednostavan delegator metoda uz pomoć __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);
?>
Rezultat izvršavanja koda:
5
Pogledajte takođe
-
metod
__callStatic,
koji presreće pozive statičkih metoda -
metod
__get,
koji presreće pristupe nepostojećim svojstvima