这篇文章主要介绍了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();
}
}
结果显示调用成功。
感谢你能够认真阅读完这篇文章,希望小编分享的“laravel框架模型中非静态方法也能静态调用的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。