简体   繁体   English

测试CodeIgniter会话变量的正确方法是什么?

[英]What is the proper way to test CodeIgniter session variable?

Take the following code snippet. 请使用以下代码段。 What is the best way to test to make sure the session variable isn't empty? 测试以确保会话变量不为空的最佳方法是什么?

<?php if ($this->session->userdata('userID')) {
   $loggedIn = 1;
}
else {
   $loggedIn = 0;
} ?>

If later in my script, I call the following, the first prints properly, but on the second I receive Message: Undefined variable: loggedIn 如果稍后在我的脚本中,我调用以下内容,第一次正确打印,但在第二次我收到消息:未定义变量:loggedIn

<?php echo $this->session->userdata('userID'));
      echo $loggedIn; ?>

I've tried using !empty and isset , but both have been unsuccessful. 我尝试过使用!emptyisset ,但两者都没有成功。 I also tried doing the if/then statement backwards using if (!($this->session->userdata('userID')) , but no dice. Any thoughts? 我也尝试使用if (!($this->session->userdata('userID'))向后执行if / then语句,但没有骰子。有什么想法吗?

Try doing the following instead: 请尝试执行以下操作:

<?php 
$loggedIn = 0;
if ($this->session->userdata('userID') !== FALSE) {
   $loggedIn = 1;
}
?>

If the error continues, you'll need to post more code in case you're calling that variable in another scope. 如果错误仍然存​​在,您将需要发布更多代码,以防您在另一个范围内调用该变量。

如果您的目的是查看是否设置了会话变量'userID' ,那么以下内容应该有效:

$this->session->userdata('userID') !== false

为什么不在会话中创建一个名为is_logged_in的布尔字段,然后检查如下:

if(false !== $this->session->userdata('is_logged_in'))
if($this->session->userdata('is_logged_in')) {
    //then condition
}

This is the proper way to test! 这是测试的正确方法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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