PHP需要来自多个目录的文件

时间:2018-04-07 08:47:40

标签: php

我已经尝试this answer关于需要多个php文件,现在我尝试从多个目录中要求多个文件,但是出现了错误..

这是我的目录树:

test
 -config
  --config_global.php
 -source
  --class
   ---class_core.php
   ---class_load.php
   ---class_test.php
  --include
   ---include_meta.php

class_core.php

<?php
require __DIR__.'/../../config/config_global.php';

class_load.php

<?php
class Load {
    public function loadClass() {
        $this->files = func_get_args();
        foreach($this->files as $file) {
            require __DIR__."/$file.php";
        }
    }

    public function loadInclude() {
        $this->files = func_get_args();
        foreach($this->files as $file) {
            require  __DIR__."/include/$file.php";
        }
    }
}

class_test.php

<?php
$sql = 'SELECT title FROM article WHERE id = 1';
$result = $con->query($sql);

include_meta.php

<?php
$sql = 'SELECT title FROM article WHERE id = 1';
$result = $con->query($sql);

config_global.php

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
define('DB_NAME', 'messageboard');
define('DB_PORT', '3306');

$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT);

的index.php

<?php
require dirname(__FILE__).'/source/class/class_core.php';
require dirname(__FILE__).'/source/class/class_load.php';
$load = new Load;
$load->loadClass('class_test');
$load->loadInclude('include_meta');

我的问题是,为什么它无法使用$con中的class_test.php变量和include_meta.php中的config_global.php

显示错误:

Undefined variable: con in /source/class/class_test.php
Undefined variable: con in /source/include/include_meta.php

1 个答案:

答案 0 :(得分:1)

尝试从$con访问您的index.php变量,它可能会有效。

您无法在->loadClass()->loadInclude()之后访问您的变量,因为您输入了内部函数。

如果您使用$con,也许您可​​以在那里访问$GLOBALS['con']变量。