laravel 理解laravel模型中的静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41143620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding static method in laravel Model
提问by Alexander Solonik
I was just going through a laravel tutrorial online and i saw the following modal coded as below:
我刚刚在网上浏览了 laravel 教程,我看到了以下编码如下的模式:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Notice extends Model {
protected $fillable = [
'provider_id',
'infringing_title',
'infringing_link',
'original_link',
'original_description',
'template',
'content_removed'
];
public static function open(array $attributes) {
return new static($attributes);
}
public function useTemplate($template) {
$this->template = $template;
}
}
What i am interested to know is what exactly is the use of the below method that is defined:
我有兴趣知道以下定义的方法的用途究竟是什么:
public static function open(array $attributes) {
return new static($attributes);
}
I realize its a static method , but this line return new static($attributes);
particularly confuses me.
我意识到它是一个静态方法,但这一行return new static($attributes);
让我特别困惑。
I see the method being used in the following way:
我看到以以下方式使用的方法:
$notice = Notice::open($date);
But i still don't quite understand its usage . can somebody explain .
但是我还是不太明白它的用法。有人可以解释一下。
回答by Sherif
static method can be used without instantiating the class thus the ::
可以在不实例化类的情况下使用静态方法,因此 ::
return new static($attributes);
makes a new model object from that class
return new static($attributes);
从该类创建一个新的模型对象
which is basically the same as
这基本上与
$notice = new Notice;
$notice->provider_id = $provider_id;
...
all you need to do with the object insatance is call $notice->save()
你需要对对象实例做的就是调用 $notice->save()
回答by Kamil Latosinski
In this case it is just a syntactic sugar. Someone doesn't seem to like the new
keyword and prefers a more semantic way to instantiate a new notice class, so it reads better.
在这种情况下,它只是一个语法糖。有人似乎不喜欢这个new
关键字,而是更喜欢用更语义化的方式来实例化一个新的通知类,所以它读起来更好。
It also leaves you the doors open for some future logic around instantiating new notice.
它还为您打开了未来关于实例化新通知的逻辑的大门。
Btw. it is model, not modal.
顺便提一句。它是模型el,而不是 mod al。