php 扩展/覆盖 Eloquent 创建方法 - 不能使静态方法非静态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19404030/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:25:30  来源:igfitidea点击:

Extend/override Eloquent create method - Cannot make static method non static

phplaravellaravel-4eloquent

提问by Marwelln

I'm overriding the create()Eloquent method, but when I try to call it I get Cannot make static method Illuminate\\Database\\Eloquent\\Model::create() non static in class MyModel.

我覆盖了create()Eloquent 方法,但是当我尝试调用它时,我得到Cannot make static method Illuminate\\Database\\Eloquent\\Model::create() non static in class MyModel.

I call the create()method like this:

我这样调用create()方法:

$f = new MyModel();
$f->create([
    'post_type_id' => 1,
    'to_user_id' => Input::get('toUser'),
    'from_user_id' => 10,
    'message' => Input::get('message')
]);

And in the MyModelclass I have this:

MyModel课堂上我有这个:

public function create($data) {
    if (!Namespace\Auth::isAuthed())
        throw new Exception("You can not create a post as a guest.");

    parent::create($data);
}

Why doesn't this work? What should I change to make it work?

为什么这不起作用?我应该改变什么才能使它工作?

回答by HenningCash

As the error says: The method Illuminate\Database\Eloquent\Model::create()is static and cannot be overridden as non-static.

正如错误所说:该方法Illuminate\Database\Eloquent\Model::create()是静态的,不能被覆盖为非静态的。

So implement it as

所以实现它

class MyModel extends Model
{
    public static function create($data)
    {
        // ....
    }
}

and call it by MyModel::create([...]);

并调用它 MyModel::create([...]);

You may also rethink if the auth-check-logic is really part of the Model or better moving it to the Controller or Routing part.

您还可以重新考虑 auth-check-logic 是否真的是模型的一部分,或者更好地将其移动到控制器或路由部分。

UPDATE

更新

This approach does not work from version 5.4.* onwards, instead follow this answer.

这种方法从 5.4.* 版本开始不起作用,而是按照这个答案

public static function create(array $attributes = [])
{
    $model = static::query()->create($attributes);

    // ...

    return $model;
}

回答by Glad To Help

Probably because you are overriding it and in the parent class it is defined as static. Try adding the word staticin your function definition:

可能是因为您覆盖了它,并且在父类中它被定义为static. 尝试static在函数定义中添加这个词:

public static function create($data)
{
   if (!Namespace\Auth::isAuthed())
    throw new Exception("You can not create a post as a guest.");

   return parent::create($data);
}

Of course you will also need to invoke it in a static manner:

当然,您还需要以静态方式调用它:

$f = MyModel::create([
    'post_type_id' => 1,
    'to_user_id' => Input::get('toUser'),
    'from_user_id' => 10,
    'message' => Input::get('message')
]);