本文实例讲述了laravel框架模型中非静态方法也能静态调用的原理.分享给大家供大家参考,具体如下:

刚开始用laravel模型时,为了方便一直写静态方法,进行数据库操作。

<?php
namespace app\models;
use illuminate\database\eloquent\model;
class user extends model
{
  public static function getlist()
  {
    return self::get()->toarray();
  }
}

直到有朋友告诉可以不用这么写,声明一个 protected 方法,方法中用 $this。在外部使用时,也可以像调静态函数一样调用。

<?php
namespace app\models;
use illuminate\database\eloquent\model;
class user extends model
{
  protected function getlist()
  {
    return $this->get()->toarray();
  }
}

试了一下,发现还真可以,按理说受保护的 protected 非静态方法,在外部是无法这么调用的 user::getlist() 。

但是在 laravel 中就可以,查看了下 model 基类的代码,原来是因为实现了 __call() 和 __callstatic() 这两个魔术方法。

class model
{
  public function __call($method, $parameters)
  {
    if (in_array($method, ['increment', 'decrement'])) {
      return $this->$method(...$parameters);
    }
    return $this->forwardcallto($this->newquery(), $method, $parameters);
  }
  public static function __callstatic($method, $parameters)
  {
    return (new static)->$method(...$parameters);
  }
}

我们试着自已实现下这两个魔术方法,看看效果。

<?php
namespace app\models;
class model
{
  //在对象中调用一个不可访问方法时,__call()被调用
  public function __call($method, $parameters)
  {
    echo '__call()';
    return $this->{$method}(...$parameters);
  }
  //在静态上下文中调用一个不可访问方法时,__callstatic()被调用
  public static function __callstatic($method, $parameters)
  {
    echo '__callstatic()';
    //注意这里,通过延迟静态绑定,仍然new了一个实例
    return (new static)->{$method}(...$parameters);
  }
  private function test()
  {
    echo '被调用了<br>';
  }
}

我们尝试调用 test() 方法。

<?php
namespace app\http\controllers\test;
use illuminate\http\request;
use app\http\controllers\controller;
use app\models\model;
class test extends controller
{
  public function index(request $request)
  {
    //对象调用
    (new model())->test();
    //静态方法调用
    model::test();
  }
}

结果显示调用成功。