Zend Framework 2 - 如何检查 cookie 是否存在?

Zend Framework 2 - How to check if a cookie exists?

如何检查 cookie 是否已经存在?

我试过了:

if (!$this->getRequest()->getCookie()->offsetExists('cookiename')) {
    // cookie exists
}

但是当cookie还不存在时,我得到以下错误:

Call to a member function offsetExists() on a non-object

我想你必须先抓取 cookie 并检查它是否真的存在。

$cookie = $this->getRequest()->getCookie();

if (empty($cookie) || !$cookie->offsetExists('cookiename')) {
   ...
}

根据 official documentation and Whosebug post,您可以像这样检查 cookie 是否存在:

if (!empty($this->getRequest()->getCookie('foo'))) {
    // cookie exists, do your stuff
}