Metode __call

Metode __call ir maģiska metode PHP, kas automātiski tiek izsaukta, mēģinot piekļūt neesošai vai nepieejamai klases metodei. Pirmo parametru tā saucamās metodes nosaukumu, otro - argumentu masīvu.

Sintakse

phppublic function __call(string $name, array $arguments) {
  // implementācija
}

Piemērs

Izveidosim klasi ar metodi __call, kas pārtvers visus izsaukumus uz neesošām metodēm:

php<?php
  class Test {
    public function __call($name, $args) {
      echo "Izsauktā metode: " . $name . "\n";
      echo "Argumenti: ";
      print_r($args);
    }
  }
  
  $test = new Test();
  $test->nonExistentMethod('a', 'b', 123);
?>

Koda izpildes rezultāts:

phpIzsauktā metode: nonExistentMethod
Argumenti: ['a', 'b', 123]

Piemērs

Implementēsim vienkāršu metožu delegātu, izmantojot __call:

php<?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("Metode $name netika atrasta");
    }
  }
  
  $math = new Math();
  echo $math->add(2, 3);
?>

Koda izpildes rezultāts:

php5

Skatiet arī

  • metode __callStatic,
    kas pārtver izsaukumus uz statiskām metodēm
  • metode __get,
    kas pārtver piekļūšanu neesošām īpašībām