为什么我在Eloquent模型中调用方法时得到“非静态方法不应该静态调用”? [英] Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?
问题描述
我试图在我的控制器中加载我的模型,并尝试这样做:
Im trying to load my model in my controller and tried this:
return Post::getAll();
得到错误非静态方法Post :: getAll()不应该被静态调用,假设$不兼容的上下文
模型中的函数如下所示:
The function in the model looks like this:
public function getAll()
{
return $posts = $this->all()->take(2)->get();
}
在控制器中加载模型的正确方法是什么?然后返回它的内容?
What's the correct way to load the model in a controller and then return it's contents?
推荐答案
您将方法定义为非静态,并尝试将其调用为静态。那就是说...
You defined your method as non-static and you are trying to invoke it as static. That said...
-
...如果你想调用静态方法,您应该使用
::
并将您的方法定义为静态。
... if you want to invoke a static method, you should use the
::
and define your method as static.
// Defining a static method in a Foo class.
public static function getAll() { /* code */ }
// Invoking that static method
Foo::getAll();
...否则,如果你想调用一个实例方法,你应该实例你的类,使用 - >
。
// 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方法都返回一个模型的实例,允许您链接方法如下所示:
Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:
$foos = Foo::all()->take(10)->get();
在该代码中,我们静态调用所有
方法通过Facade。之后,所有其他方法被称为实例方法。
In that code we are statically calling the all
method via Facade. After that, all other methods are being called as instance methods.
这篇关于为什么我在Eloquent模型中调用方法时得到“非静态方法不应该静态调用”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!