`if(isset($ _ SESSION))`和`if($ _SESSION)`之间的区别? [英] Difference between `if (isset($_SESSION))` and `if ($_SESSION)`?

查看:555
本文介绍了`if(isset($ _ SESSION))`和`if($ _SESSION)`之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到人们经常写

<?php  if($_SESSION['username']) {...} ?>

我一直在使用:

 <?php if(isset($_SESSION['username'])) {...} ?> 

有人可以在检查是否设置了变量时解释了差异吗(这就是我要使用的变量)?

解决方案

根据PHP.net,isset()执行以下操作:

确定是否设置了变量并且该变量不为NULL.

写作时:

<?php  if($_SESSION['username']) {...} ?>

您正在检查$ _SESSION ['username']是否等于true.换句话说,您正在检查该值是否不等于false.

根据 PHP.net ,以下内容被认为是错误的:

转换为布尔值时,以下值为FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

如您所见,未设置的变量/NULL变量被视为FALSE.因此,通过测试$ _SESSION元素是否为真,您还可以确定它是否存在.

另一方面,Isset实际上检查变量是否存在.如果您想知道是否存在该名称的SESSION变量,请使用isset()作为测试TRUE/FALSE的变量,而不取决于该变量是否存在.

再看下面的例子:

$_SESSION['a'] = FALSE;
if($_SESSION['a']){
echo 'Hello'; //This line is NOT echo'd.
}

if(isset($_SESSION['b'])){
echo 'Hello'; //This line is NOT echo'd because $_SESSION['b'] has not been set.
}

I've noticed that frequently people simply write

<?php  if($_SESSION['username']) {...} ?>

while I have been using:

 <?php if(isset($_SESSION['username'])) {...} ?> 

Could someone explain the difference when checking if a variable is set (that's what I'd be using it for)?

解决方案

According to PHP.net, isset() does the following:

Determine if a variable is set and is not NULL.

When writing:

<?php  if($_SESSION['username']) {...} ?>

You are checking to see if $_SESSION['username'] is equal to true. In other words, you are checking if the value does not equal false.

According to PHP.net the following are considered FALSE:

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

As you can see unset variables / NULL variables are considered FALSE. Therefore by testing if the $_SESSION element is true, you are also determining if it exists.

Isset, on the otherhand, actually checks if the variable exists. If you would like to know if there is a SESSION variable by that name, use isset() as testing it for TRUE/FALSE isn't dependent on whether the variable exists or not.

Further, look at the following examples:

$_SESSION['a'] = FALSE;
if($_SESSION['a']){
echo 'Hello'; //This line is NOT echo'd.
}

if(isset($_SESSION['b'])){
echo 'Hello'; //This line is NOT echo'd because $_SESSION['b'] has not been set.
}

这篇关于`if(isset($ _ SESSION))`和`if($ _SESSION)`之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆