This situation is especially common in larave, but during the development process it is obvious that some of these are not static. For example, if you use a model User, then every time you instantiate it, it will be a brand new one and will not affect each other. A magic method __callStatic is used here.
For example:
<?php class Test{ public function __call($name, $arguments) { echo 'this is __call'. PHP_EOL; } public static function __callStatic($name, $arguments) { echo 'this is __callStatic:'. PHP_EOL; } } $test = new Test(); $test->hello(); $test::hi(); //this is __call:hello //this is __callStatic:hi
Of course, the magic method is also a very performance-intensive method. Every time it is called, scan the class first. It will be called only when a method is found, and this method can also be of great help for the neatness and abstraction of the code. There must be a trade-off between this.
The log class implemented below uses this A method, decouple the method, and you can call it as long as it meets the specified interface
<?php class Test{ //获取 logger 的实体 private static $logger; public static function getLogger(){ return self::$logger?: self::$logger = self::createLogger(); } private static function createLogger(){ return new Logger(); } public static function setLogger(LoggerInterface $logger){ self::$logger = $logger; } public function __call($name, $arguments) { call_user_func_array([self::getLogger(),$name],$arguments); } public static function __callStatic($name, $arguments) { forward_static_call_array([self::getLogger(),$name],$arguments); } } interface LoggerInterface{ function info($message,array $content = []); function alert($messge,array $content = []); } class Logger implements LoggerInterface { function info($message, array $content = []) { echo 'this is Log method info' . PHP_EOL; var_dump($content); } function alert($messge, array $content = []) { echo 'this is Log method alert: '. $messge . PHP_EOL; } } Test::info('喊个口号:',['好好','学习','天天','向上']); $test = new Test(); $test->alert('hello');
Output:
this is Log method info array(4) { [0]=> string(6) "好好" [1]=> string(6) "学习" [2]=> string(6) "天天" [3]=> string(6) "向上" } this is Log method alert: hello
Recommended learning:php video tutorial
The above is the detailed content of How to use the __callStatic function in php. For more information, please follow other related articles on the PHP Chinese website!