0

我在 PHP 中的变量范围设置方面遇到了一些问题。这是我的代码结构——

<?php
$loader = new ELLoad();
$sessionid = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
    global $loader;
    $loader->load($file['text']);
    global $sessionid;
    $sessionid = $loader->getSessionId();
} 
if (strcasecmp($method, "extract") == 0) {
    $extractor = new ELExtract();
    global $sessionid;
    $extractor->extract($sessionid); //$session id for some reason is still ' ' here
}

来自客户端的请求序列始终是加载后提取。谁能告诉我为什么我的 $sessionid 变量可能没有得到更新吗?

4

2 回答 2

1

$sessionid仍然是'',因为如果first condition==它不会改变false

改进您的代码:

$loader = new ELLoad();
$sessionid = $loader->getSessionId();
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
    $loader->load($file['text']);
    // do more stuff
}
else if (strcasecmp($method, "extract") == 0) {
    $extractor = new ELExtract();
    $extractor->extract($sessionid);
    // do more stuff
}

此外,最好使用$_GET$_POST取决于您的情况,而不是$_REQUEST最终else if在单独和重复的条件下使用。

于 2013-08-28T16:58:15.730 回答
0

global $...除非你在一个函数中,否则你不必声明。一个块(if, while, ...)与之前的行具有相同的范围。

我不知道你想做什么,但你必须$sessionid在真正的会话中保持满足,比如:

<?php
session_start();
$loader = new ELLoad();
$_SESSION['id'] = '';
$method = $_REQUEST['m'];
if (strcasecmp($method, "getfile") == 0) {
    $loader->load($file['text']);
    $_SESSION['id']  = $loader->getSessionId();
} 
if (strcasecmp($method, "extract") == 0) {
    $extractor = new ELExtract();
    $extractor->extract($_SESSION['id']); //$session id for some reason is still ' ' here
}
于 2013-08-28T16:50:54.447 回答