__call 메서드

__call 메서드는 PHP의 마법 메서드로, 클래스의 존재하지 않거나 접근 불가능한 메서드에 접근하려고 할 때 자동으로 호출됩니다. 첫 번째 매개변수로 호출된 메서드의 이름을, 두 번째 매개변수로 인수 배열을 받습니다.

구문

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

예제

존재하지 않는 모든 메서드 호출을 가로채는 __call 메서드가 있는 클래스를 만들어 봅시다:

php<?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);
?>

코드 실행 결과:

phpCalled method: nonExistentMethod
Arguments: ['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