从$ _SESSION获取变量会引发错误

时间:2012-05-08 07:39:47

标签: php

在将$_SESSION['var']传递给函数时,如果$_SESSION['var']未设置,我会收到通知:

Notice: Undefined index: var in scripname.php on line 49

是否有更安全的方法来获取$_SESSION['var'],如果0未设置,这会给我$_SESSION['var']

提前谢谢!!

6 个答案:

答案 0 :(得分:5)

$var = isset($_SESSION['var']) ? $_SESSION['var'] : 0

答案 1 :(得分:3)

if (isset($_SESSION['var']))
{
    echo "session is set";
}
else
{
    echo "session is not set";
}

答案 2 :(得分:1)

if (isset($_SESSION['var'])){
    // Do something
}

答案 3 :(得分:0)

if(!array_key_exists('var',$_SESSION))
{
    $var = 0;
}
else
{
    $var = $_SESSION['var'];
}

答案 4 :(得分:0)

使用

if(isset($_SESSION['var']))
    // do

答案 5 :(得分:0)

怎么样:

$var = @$_SESSION['var'];