Difference between `if (isset($_SESSION))` and `if ($_SESSION)`?

前端 未结 3 2054
小蘑菇
小蘑菇 2021-01-18 02:11

I\'ve noticed that frequently people simply write


while I have been using:



        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-18 02:35

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

    Determine if a variable is set and is not NULL.

    When writing:

    
    

    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.
    }
    

提交回复
热议问题