我刚刚在网上浏览了一个 laravel tutrorial,我看到了以下编码如下的模态:
<?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;
}
}
我想知道的是下面定义的方法到底有什么用:
public static function open(array $attributes) {
return new static($attributes);
}
我意识到它是一个静态方法,但是 return new static($attributes);
这一行特别让我感到困惑。
我看到以下列方式使用的方法:
$notice = Notice::open($date);
但是我还是不太明白它的用法。有人可以解释一下吗。
最佳答案
可以在不实例化类的情况下使用静态方法,因此 ::
return new static($attributes);
从该类创建一个新的模型对象
基本和
一样$notice = new Notice;
$notice->provider_id = $provider_id;
...
您需要对对象实例做的就是调用 $notice->save()
关于php - 了解 laravel 模型中的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41143620/