doutang7707 2012-05-07 23:50
浏览 86
已采纳

`if(isset($ _ SESSION))`和`if($ _SESSION)`之间的区别?

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)?

  • 写回答

3条回答 默认 最新

  • doujiang1939 2012-05-08 00:17
    关注

    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.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测