gpt4 book ai didi

php - 为什么在 Eloquent 模型中调用方法时得到 'Non-static method should not be called statically'?

转载 作者:IT老高 更新时间:2023-10-28 12:05:18 26 4
gpt4 key购买 nike

我试图在我的 Controller 中加载我的模型并尝试了这个:

return Post::getAll();

得到错误不应静态调用非静态方法 Post::getAll(),假设 $this 来自不兼容的上下文

模型中的函数如下所示:

public function getAll()
{

return $posts = $this->all()->take(2)->get();

}

在 Controller 中加载模型然后返回其内容的正确方法是什么?

最佳答案

您将您的方法定义为非静态的,并尝试将其作为静态调用。那就是……

1.如果你想调用静态方法,你应该使用::并将你的方法定义为静态。

// Defining a static method in a Foo class.
public static function getAll() { /* code */ }

// Invoking that static method
Foo::getAll();

2.否则,如果你想调用一个实例方法,你应该实例化你的类,使用->

// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }

// Invoking that non-static method.
$foo = new Foo();
$foo->getAll();

注意:在 Laravel 中,几乎所有 Eloquent 方法都会返回模型的一个实例,允许您将方法链接起来,如下所示:

$foos = Foo::all()->take(10)->get();

在该代码中,我们静态地通过 Facade 调用 all 方法。之后,所有其他方法都被称为实例方法

关于php - 为什么在 Eloquent 模型中调用方法时得到 'Non-static method should not be called statically'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18339716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com