简体   繁体   中英

Confuse about Yii2 session

I use Yii2 framework to do my PHP project. But I ran into some trouble. Here is my code. First, set session variable through yii2 session api like this:

Yii::$app->session->set('test', 123);

Then in other action, I hope to get this variable:

var_dump(Yii::$app->session);

@session_start();
var_dump($_SESSION);

var_dump(Yii::$app->session['test']);

But I found the the result:

object(yii\web\Session)#109 (6) {
  ["flashParam"]=>
  string(7) "__flash"
  ["handler"]=>
  NULL
  ["_cookieParams":"yii\web\Session":private]=>
  array(1) {
    ["httponly"]=>
    bool(true)
  }
  ["_hasSessionId":"yii\web\Session":private]=>
  NULL
  ["_events":"yii\base\Component":private]=>
  array(0) {
  }
  ["_behaviors":"yii\base\Component":private]=>
  NULL
}
array(2) {
  ["__flash"]=>
  array(0) {
  }
  ["test"]=>
  int(123)
}
int(123)

I wondered why Yii::$app->session CAN NOT dump the value of the key 'test' at the first var_dump.

For retrieve a session entry Try using session->get()

 $app->session->get('test') ; 

eg:

var_dump( $app->session->get('test')  );

take a look at this guide for some sample and suggestion http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM