我在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变量可能没有得到更新吗?
$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
。
除非在函数中,否则不必声明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
}