0

以下脚本适用于 windows xampp, php 5.3.8

session_start();
    if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
        $myvar = "some_value";
    } elseif (!empty($_GET['myvar'])) {
        $_SESSION['myvar'] = $_GET['myvar'];
    }
    $_SESSION['myvar'] = $myvar;

但在 ubuntu 服务器上,如果我var_dump($myvar)的值为php 5.3.10null

4

3 回答 3

1

您是否考虑过您可能会定义会话变量两次,覆盖 if 语句中定义的第一个变量?此外,如果您在 !empty($_GET['myvar']) 为真时运行以下代码:

session_start();
if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
    $myvar = "some_value";
} elseif (!empty($_GET['myvar'])) {
    $_SESSION['myvar'] = $_GET['myvar'];
}
$_SESSION['myvar'] = $myvar;

您很可能会收到未定义的变量警告,因为您没有设置 $myvar. 尝试这个:

session_start();
if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
    $myvar = "some_value";
    $_SESSION['myvar'] = $myvar;
} elseif (!empty($_GET['myvar'])) {
    $_SESSION['myvar'] = $_GET['myvar'];
}
于 2013-06-11T12:52:47.507 回答
0

$myvar仅当 session 或 get 参数为空时才添加值。否则为空。这个怎么样:

session_start();
$my_var = isset($_SESSION['my_var'] ? $_SESSION['my_var'] : 'default_value';
if(empty($_SESSION['myvar']) && empty($_GET['myvar'])){
    $myvar = 'some_value';
} elseif(!empty($_GET['my_var'))) {
    $myvar = $_GET['myvar'];
}
$_SESSION['my_var'] = $myvar;

或者简单地说:

session_start();
$_SESSION['my_var'] = isset($_GET['my_var']) ? $_GET['my_var'] : (isset($_SESSION['my_var']) ? $_SESSION['my_var'] : 'default_value');
于 2013-06-11T12:50:38.377 回答
0
empty($_SESSION['myvar']) && empty($_GET['myvar'])

一直都是假的。因为第一次 $_SESSION['myvar'] 为空,而 $_GET['myvar'] 不为空:</p>

$_SESSION['myvar'] = $myvar; // now $myvar is empty



 if (empty($_SESSION['myvar']) && empty($_GET['myvar'])) {
        $_SESSION['myvar'] = "some_value";
    } elseif (!empty($_GET['myvar'])) {
        $_SESSION['myvar'] = $_GET['myvar'];
    }
于 2013-06-11T12:52:39.343 回答