__callメソッド

メソッド__callは、PHPのマジックメソッドの一つで、クラスの存在しないメソッドまたはアクセス不可能なメソッドへの呼び出しが試みられた際に自動的に呼び出されます。第一引数には呼び出されたメソッド名を、第二引数には引数の配列を受け取ります。

構文

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

例

存在しないメソッドの全ての呼び出しをインターセプトする__callメソッドを持つクラスを作成します:

php<?php
  class Test {
    public function __call($name, $args) {
      echo "呼び出されたメソッド: " . $name . "\n";
      echo "引数: ";
      print_r($args);
    }
  }
  
  $test = new Test();
  $test->nonExistentMethod('a', 'b', 123);
?>

コードの実行結果:

php呼び出されたメソッド: nonExistentMethod
引数: ['a', 'b', 123]

例

__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("Method $name not found");
    }
  }
  
  $math = new Math();
  echo $math->add(2, 3);
?>

コードの実行結果:

php5

関連項目

  • メソッド__callStatic,
    静的メソッドの呼び出しをインターセプトします
  • メソッド__get,
    存在しないプロパティへのアクセスをインターセプトします