在 CodeIgniter 3.x 中使用 empty() 和 isset() 检查会话变量

Checking session variables with empty() and isset() in CodeIgniter 3.x

对于 CodeIgniter 3.0.3,文档指出可以通过几种不同的方式检索会话数据,包括 $_SESSION['item']$this->session->item。这是真的。无论我如何设置会话变量,我发现我可以双向回显该值。

现在,填充该会话变量后,我可以像这样检查空条件:if(empty($_SESSION['item'])),它的计算结果如我所料,为 bool(false)。但是,如果我以这种方式检查同一个会话变量:if(empty($this->session->item)),它的计算结果为 bool(true),这不是我所期望的(因为我可以在下一行回显它的值)。为什么这两种不同的检查空条件的方法被不同地评估?

这是由于 empty() 的工作原理。比较这个报价:

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it's noted in the documentation above, I think it's worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add __isset() magic function to your class:

(摘自php.net:http://php.net/manual/en/function.empty.php,来自用户 Janci 的评论)