Metoda __call
Metoda __call je magična metoda v PHP-ju, ki se samodejno pokliče, ko poskušamo dostopati do neobstoječe ali nedostopne metode razreda. Kot prvi parameter sprejme ime klicane metode, kot drugega pa polje argumentov.
Sintaksa
public function __call(string $name, array $arguments) {
// implementacija
}
Primer
Ustvarimo razred z metodo __call, ki bo prestregla vse klice neobstoječih metod:
<?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);
?>
Rezultat izvajanja kode:
Called method: nonExistentMethod
Arguments: ['a', 'b', 123]
Primer
Implementirajmo preprost delegator metod z uporabo __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 izvajanja kode:
5
Glejte tudi
-
metoda
__callStatic,
ki prestreza klice statičnih metod -
metoda
__get,
ki prestreza dostope do neobstoječih lastnosti