我感觉百度到的关于yii2的cookie,都没法照用好像,特来求助

图片描述

图片描述

上面那,是百度到的,手册上也是这么写的,我的情况是如下,照着写压根取不到值好像/。

图片描述

图片描述

划红线那,name或者value,我怎么取到呢?

求教各位高人,谢谢

新截图,下面第一张是存的,第二张是准备取的,我该怎么判断?那个add,是我用户名就是那个,问题是换了名字咋搞啊?我想不明白咋解决,特来求助

![图片描述][6]

图片描述

图片描述

阅读 2.7k
2 个回答
//写
$cookie = \Yii::$app->response->cookies;
$cookie->add(new Cookie(['name'=>'userName','value'=>'张三']));
$cookie->add(new Cookie(['name'=>'userId','value'=>123]));
//读
$cookie = \Yii::$app->request->cookies;
echo $cookie->get('userName');
echo $cookie->get('userId');

谢邀,很久没在这边回答了。

        $cookie = \Yii::$app->getRequest()->getCookies();
        $cookie->get("asd")->name;
        $cookie->get("asd")->value;
        $cookie->getValue("asd",'这是一个默认值');

这里的$cookie是一个CookieCollection对象,支持获取collection中的cookie对象,第四行中的getValue的实现其实源码里面很简单

yii2/web/CookieCollection.php[91]

    /**
     * Returns the value of the named cookie.
     * @param string $name the cookie name
     * @param mixed $defaultValue the value that should be returned when the named cookie does not exist.
     * @return mixed the value of the named cookie.
     * @see get()
     */
    public function getValue($name, $defaultValue = null)
    {
        return isset($this->_cookies[$name]) ? $this->_cookies[$name]->value : $defaultValue;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进