Metode __call

Metode __call adalah metode ajaib (magic method) dalam PHP yang secara otomatis dipanggil ketika ada upaya untuk mengakses metode kelas yang tidak ada atau tidak dapat diakses. Parameter pertamanya menerima nama metode yang dipanggil, parameter kedua - array argumen.

Sintaks

phppublic function __call(string $name, array $arguments) {
  // implementasi
}

Contoh

Mari buat kelas dengan metode __call yang akan mengintercept semua panggilan ke metode yang tidak ada:

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

Hasil eksekusi kode:

phpMetode yang dipanggil: nonExistentMethod
Argumen: ['a', 'b', 123]

Contoh

Mari implementasikan delegator metode sederhana menggunakan __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 tidak ditemukan");
    }
  }
  
  $math = new Math();
  echo $math->add(2, 3);
?>

Hasil eksekusi kode:

php5

Lihat juga

  • metode __callStatic,
    yang mengintercept panggilan metode statis
  • metode __get,
    yang mengintercept akses ke properti yang tidak ada