__callStatic 메서드
__callStatic 메서드는 존재하지 않거나 접근할 수 없는 정적 메서드를 호출하려고 할 때 PHP에서 자동으로 호출되는 매직 메서드입니다. 첫 번째 매개변수로 호출된 메서드의 이름을, 두 번째 매개변수로 전달된 인수들의 배열을 받습니다.
구문
public static function __callStatic(string $name, array $arguments);
예제
__callStatic 메서드가 있는 클래스를 만들고 존재하지 않는 정적 메서드를 호출해 보겠습니다:
<?php
class MyClass {
public static function __callStatic($name, $args) {
echo "Called static method '$name' with arguments: ";
print_r($args);
}
}
MyClass::nonExistentMethod(1, 2, 3);
?>
코드 실행 결과:
Called static method 'nonExistentMethod' with arguments: [1, 2, 3]
예제
다른 타입의 객체를 생성하기 위한 간단한 파사드를 구현해 보겠습니다:
<?php
class Factory {
public static function __callStatic($name, $args) {
if (strpos($name, 'create') === 0) {
$className = substr($name, 6);
return new $className(...$args);
}
throw new Exception("Method $name not found");
}
}
class User {}
$user = Factory::createUser();
var_dump($user instanceof User);
?>
코드 실행 결과:
true