laravel 未定义的属性:App\Http\Controllers\MyController::$cookieJar
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38344865/
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
Undefined property: App\Http\Controllers\MyController::$cookieJar
提问by Coffee
So my controller looks as follows:
所以我的控制器如下所示:
use Illuminate\Http\Request;
use Illuminate\Cookie\CookieJar;
use Cookie;
class MyController extends Controller {
public function __construct(CookieJar $cookieJar)
{
$this->id = $this->getID();
$this->cookieJar = $cookieJar;
}
private function getID()
{
if (!isset($_COOKIE["ID"])){
$id = 20;
$this->cookieJar->queue('ID', $id, 60);
}
return $id;
}
But I keep getting an error
但我不断收到错误
Undefined property: App\Http\Controllers\MyController::$cookieJar
未定义的属性:App\Http\Controllers\MyController::$cookieJar
In getID function.
在 getID 函数中。
What am I doing wrong? Would highly appreciate any possible help!
我究竟做错了什么?非常感谢任何可能的帮助!
采纳答案by Lakhwinder Singh
Basically problem in your code not that cookieJar class. Below is the correct code for controller:
您的代码中的问题基本上不是那个 cookieJar 类。以下是控制器的正确代码:
use Illuminate\Http\Request;
use Illuminate\Cookie\CookieJar;
use Cookie;
class MyController extends Controller {
protected $id;
protected $cookieJar;
public function __construct(CookieJar $cookieJar)
{
$this->cookieJar = $cookieJar;
$this->id = $this->getID();
}
private function getID()
{
if (!isset($_COOKIE["ID"])){
$id = 20;
$this->cookieJar->queue('ID', $id, 60);
}
return $id;
}
When we are using any property in all the functions of controllers for carry some value then we have to define these properties. Please check my code.
One more thing, the order of properties also incorrect in constructor method. Because you are using a function getID()
which is using $cookieJar
property. So you have to define that property first then use second property $id
in constructor method.
当我们在控制器的所有功能中使用任何属性来携带一些值时,我们必须定义这些属性。请检查我的代码。还有一件事,构造函数方法中的属性顺序也不正确。因为您正在使用一个getID()
正在使用$cookieJar
属性的函数。因此,您必须首先定义该属性,然后$id
在构造函数方法中使用第二个属性。
I think this will be helpful for you.
我认为这对你有帮助。
回答by Wouter Van Damme
In your controller, you call the getID method, and in the getID method, you use your cookiejar, but the cookiejar has not yet been initialised.
在您的控制器中,您调用 getID 方法,在 getID 方法中,您使用您的 cookiejar,但 cookiejar 尚未初始化。
If you switch the method calls around, it should work
如果您切换方法调用,它应该可以工作
public function __construct(CookieJar $cookieJar)
{
$this->cookieJar = $cookieJar;
$this->id = $this->getID();
}