__callStatic()はマジックメソッドの一つで、実行させようとしたクラスのstaticメソッドが存在しない時に呼ばれる。
以下の例では、MyClassに__callStatic()メソッドのみが定義されている。__callStatic()の内容は、引数の$methodと$argsを表示させるようにしている。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php class MyClass { public static function __callStatic($method, $args) { echo '$method:'; var_export($method); echo PHP_EOL; echo '$args:' . PHP_EOL; var_export($args); echo PHP_EOL; } } |
このクラスに存在しないstaticメソッドを、引数なし、引数1個、2個で実行した場合の実行結果。引数は配列として$argsにセットされ、引数がない場合は空の配列、引数が1個の場合は要素数1(要素番号0)の配列となる。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
MyClass::method1(); // $method:'method1' // $args: // array ( // ) MyClass::myMethod(1); // $method:'myMethod' // $args: // array ( // 0 => 1, // ) MyClass::myMethod(1, "two"); // $method:'myMethod' // $args: // array ( // 0 => 1, // 1 => 'two', // ) |
インスタンスに対して存在しないstaticメソッドを呼んで__callStatic()が実行される場合、通常のstaticメソッドと違って'->'はエラーになる。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php class MyClass { public static function static_method() { echo "static method\n"; } public static function __callStatic($method, $args) { echo "__callStatic called.\n"; } } $instance = new MyClass(); $instance->static_method(); // static method $instance::static_method(); // static method $instance::method1('undefined static method'); //__callStatic called. $instance->method1('undefined static method'); // Uncaught Error: Call to undefined method MyClass::method1() |