包含文件包含它包含的文件?

时间:2013-12-15 01:12:40

标签: php class object include

我有 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.class.php 中包含的 config.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 变量本身不是。为什么呢?

1 个答案:

答案 0 :(得分:0)

将config作为返回变量放置到函数中

function getConfig(){
   $config['database'] = array (
     'host' => 'localhost',
     'user' => 'root',
     'pass' => '',
     'db' => 'game'
   );
   return $config;
}

然后在课堂上你可以使用:

   $config = getConfig();
   return $config[$name];

我将var_dump($config);放在两者 config.class和core.class的顶部。如果我只是在浏览器中加载config.class,我会得到

array (size=1)
  'database' => 
    array (size=4)
      'host' => string 'localhost' (length=9)
      'user' => string 'root' (length=4)
      'pass' => string '' (length=0)
      'db' => string 'game' (length=4)

array (size=1)
  'database' => 
    array (size=4)
      'host' => string 'localhost' (length=9)
      'user' => string 'root' (length=4)
      'pass' => string '' (length=0)
      'db' => string 'game' (length=4)
相关问题