在读取cookie时不在对象上下文中使用$this



我试图读取Component中的cookie,却在Cookie类中得到错误?

Using $this when not in object context
COREsrcHttpCookieCookie.php:738

[![在此输入图像描述][1]][1]

代码:

<?php
namespace WetKitControllerComponent;
use CakeControllerComponent;
use CakeControllerComponentAuthComponent;
use CakeCoreConfigure;
use CakeI18nI18n;
use CakeI18nTime;
use CakeORMEntity;
use CakeUtilityText;
use CakeHttpCookieCookie;
use CakeHttpCookieCookieCollection;
class WetKitComponent extends Component
{
public function init($configs = [])
{
...
debug(Cookie::read("wetkit.lang"));
...
}
...
}

编辑2

带有以下代码:

$cookieInstance = new Cookie('test'); 
debug($cookieInstance->read("wetkit.lang"));

我得到:

Invalid data type, must be an array or ArrayAccess instance.
InvalidArgumentException
Toggle Vendor Stack Frames
COREsrcUtilityHash.php:52

编辑3

如果我像这样将请求传递给我的组件:

//Setting core values for project
$this->appData = $this->WetKit->init([
'request' => $this->request,
...
]);

然后,在我的组件中:

debug($configs['request']->getCookie('wetkit.lang'));

我不再收到错误,它将输出null。不确定这是否是一种有效的方法。

除了不正确的代码使用之外,组件可以访问它们所连接的控制器,从那里你可以获得请求对象,然后你可以从中读取cookie。

$this->getController()->getRequest()->getCookie('wetkit.lang')

另请参见

  • 食谱>控制器>组件>访问组件的控制器
  • 食谱>请求&响应对象>Cookie

最新更新