>  기사  >  백엔드 개발  >  PHP에서 __callStatic 함수를 사용하는 방법

PHP에서 __callStatic 함수를 사용하는 방법

醉折花枝作酒筹
醉折花枝作酒筹앞으로
2021-07-12 15:20:191531검색

이 상황은 특히 Larave에서 흔히 발생하지만 개발 과정에서 이들 중 일부는 정적이 아니라는 것이 분명합니다. 예를 들어 모델 사용자를 사용하면 이를 인스턴스화할 때마다 새로운 것이 됩니다. 여기에는 __callStatic이라는 매직 메서드가 사용됩니다.

PHP에서 __callStatic 함수를 사용하는 방법

예:

<?php
class Test{
    public function __call($name, $arguments)
    {
        echo &#39;this is __call&#39;. PHP_EOL;
    }

    public static function __callStatic($name, $arguments)
    {
        echo &#39;this is __callStatic:&#39;. PHP_EOL;
    }
}

$test = new Test();
$test->hello();
$test::hi();
//this is __call:hello
//this is __callStatic:hi

물론 매직 메서드는 호출될 때마다 클래스를 검색하고 메서드를 찾을 수 없을 때만 호출됩니다. 깔끔함과 코드 단순성을 위해 이 메서드를 추상화하는 것도 큰 도움이 될 수 있지만, 아래에 구현된 로그 클래스는 이 메서드를 채택하고 있으며 충족하는 한 호출할 수 있습니다.

<?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 &#39;this is Log method info&#39; . PHP_EOL;
        var_dump($content);
    }

    function alert($messge, array $content = [])
    {
        echo &#39;this is Log method alert: &#39;. $messge . PHP_EOL;
    }
}


Test::info(&#39;喊个口号:&#39;,[&#39;好好&#39;,&#39;学习&#39;,&#39;天天&#39;,&#39;向上&#39;]);
$test = new Test();
$test->alert(&#39;hello&#39;);

출력:

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

추천 학습:

php 비디오 튜토리얼

위 내용은 PHP에서 __callStatic 함수를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제