注册 登陆

    2021-03-16 22:36:26PHP 魔术方法 __call 与 __callStatic 方法

    您现在的位置是: 首页 >  php >  PHP 魔术方法 __call 与 __callStatic 方法

    1. __call 当要调用的方法不存在或权限不足时,会自动调用__call 方法。
    2. __callStatic 当调用的静态方法不存在或权限不足时,会自动调用__callStatic方法。
    3. class Animal
      {
      private function eat()
      {
      echo 'eat';
      }

      public function __call($name, $arguments)
      {
      echo '调用不存在的方法名是:' . $name . '<br>参数是:';
      print_r($arguments);
      echo '<br>';
      }

      public static function __callStatic($name, $arguments)
      {
      echo '调用不存在的--静态--方法名是:' . $name . '<br>参数是:';
      print_r($arguments);
      }
      }

      $animal = new Animal();
      $animal->drink([1, 2, 3]);
      // 调用不存在的方法名是:drink
      // 参数是:Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) )

      Animal::smile(['可爱', '大笑', '微笑']);
      // 调用不存在的--静态--方法名是:smile
      // 参数是:Array ( [0] => Array ( [0] => 可爱 [1] => 大笑 [2] => 微笑 ) )

      这里说一下我看到的 __callStatic 应用场景

      扩展类中的方法 在tp5框架 Log.php 中

    4. /**
      * 静态调用
      * @param $method
      * @param $args
      * @return mixed
      */
      public static function __callStatic($method, $args)
      {
      // 类变量$type = ['log', 'error', 'info', 'sql', 'notice', 'alert', 'debug'];
      if (in_array($method, self::$type)) {
      array_push($args, $method);
      return call_user_func_array('\\think\\Log::record', $args);
      }
      }

      样就可以扩展出 Log::log()、Log::error()...等7个方法

      还有一种用法,可以看 tp5 框架 Db.php 文件最下面,** 可以调用其他类的方法 **

    5. // 调用驱动类的方法
      public static function __callStatic($method, $params)
      {
      // 自动初始化数据库
      return call_user_func_array([self::connect(), $method], $params);
      }

      今天看到监听 sql 代码的时候,发现 \think\Db 下面没有 listen 方法,当我们调用\think\Db::listen 的时候,实际调用的是 Connection 类中的 listen 方法

      上述代码 self::connect() 返回的是一个连接对象,$method 是这个对象中的方法,构成 call_user_func_array([对象,方法],参数)

      顺便附上 call_user_func_array 这个函数的使用文档

关键字词: PHP 魔术方法 __call 与 __callStatic 方法,tp5 __callStatic

0