【发布时间】:2013-12-15 01:12:39
【问题描述】:
我有这个 source_folder/config.php 文件:
<?php
$config['database'] = array (
'host' => 'localhost',
'user' => 'root',
'pass' => '',
'db' => 'game'
);
?>
这个source_folder/class/core.class.php文件:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'config.php';
function __autoload($sName) {
$aName = explode('_',$sName);
if($aName[0] == 'Model')
include_once $_SERVER['DOCUMENT_ROOT'].'class/model/' . strtolower($aName[1]) . '.class.php';
elseif($aName[0] == 'View')
include_once $_SERVER['DOCUMENT_ROOT'].'class/view/' . strtolower($aName[1]) . '.class.php';
elseif($aName[0] == 'Controller')
include_once $_SERVER['DOCUMENT_ROOT'].'class/controller/' . strtolower($aName[1]) . '.class.php';
elseif($aName[0] == 'Core')
include_once $_SERVER['DOCUMENT_ROOT'].'class/' . strtolower($aName[1]) . '.class.php';
}
class Core {
}
还有这个 source_folder/class/config.class.php 文件:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'class/core.class.php';
/**
* Description of config
*
* @author Lysy
*/
class Core_Config extends Core {
static function GetConfigArray($name) {
return $config[$name];
}
}
?>
当我将var_dump($config['database']); 放入 core.class.php 时,结果是变量的转储。但是当我将var_dump(Core_Config::GetConfigArray('database')); 放在任何地方时,它会转储为NULL。哪里有问题? config.php 是否包含在 core.class.php 中是否也包含在 config.class.php 中,因为它包含 core.class。 php?据我所知,它应该是,但似乎不是。
编辑:我还尝试将 var_dump($config['database']); 放入 config.class.php但它也转储为 NULL。
编辑 2: 我使用
class Core {
static public function getWholeConfig() {
global $config;
return $config;
}
}
在core.class.php文件和
static function GetConfigArray($name) {
$config = Core::getWholeConfig();
return $config[$name];
}
在 config.class.php 文件中,但我仍然不明白为什么最后一个文件没有看到 $config 变量。我的意思不是在类范围内,而是在任何地方,这个变量包含在 core.class.php 中,虽然 core.class.php 包含在 config 中。 class.php 变量本身不是。为什么?
【问题讨论】:
-
这是关于函数中变量的可用性,我知道我不能返回
$config[$name],因为变量是在类和方法的范围之外声明的。但是为什么当我尝试将变量转储到类之外的同一个文件中时,它转储为 NULL? -
$config 数组在实际全局范围内的存在取决于调用包含脚本的位置。默认情况下,包含的脚本不在全局范围内运行。自动加载器具有本地函数范围。