我已经尝试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
答案 0 :(得分:1)
尝试从$con
访问您的index.php
变量,它可能会有效。
您无法在->loadClass()
和->loadInclude()
之后访问您的变量,因为您输入了内部函数。
如果您使用$con
,也许您可以在那里访问$GLOBALS['con']
变量。