如何处理;单独包括;来自php中的不同文件?
一个如何处理;单独包括;来自php中的不同文件?,php,include,require,include-path,Php,Include,Require,Include Path,一个index.php文件有许多包含文件,在其中一些包含文件中,有一些变量属于包含index.php的文件。我只能将“包含代码”写入index.php文件或插入“包含代码”所有包含index.php文件的单独文件吗?可能很难理解我写了什么,但这是我的文件夹和代码: 我的文件夹和文件在这里: / | + includes/ | | | + initialize.php | + functions.php | + config.php | + layouts/ | | | +
index.php
文件有许多包含文件,在其中一些包含文件中,有一些变量属于包含index.php
的文件。我只能将“包含代码”写入index.php
文件或插入“包含代码”所有包含index.php
文件的单独文件吗?可能很难理解我写了什么,但这是我的文件夹和代码:
我的文件夹和文件在这里:
/
|
+ includes/
| |
| + initialize.php
| + functions.php
| + config.php
|
+ layouts/
| |
| + header.php
| + sidebar.php
| + content.php
| + footer.php
|
+ images/
| |
| + image1.jpg
|
+ index.php
下面是我的initialize.php:
//initialize.php
<?php
defined('DS') ? null : define('DS', '/');
defined('SITE_ROOT') ? null :
define('SITE_ROOT', '/webspace/httpdocs');
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
require_once(LIB_PATH.DS.'config.php');
require_once(LIB_PATH.DS.'functions.php');
?>
//initialize.php
这里是function.php
//function.php
<?php
function include_layout_template($template="") {
include(SITE_ROOT.DS.'layouts'.DS.$template);
}
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = LIB_PATH.DS."{$class_name}.php";
if(file_exists($path)) {
require_once($path);
} else {
die("The file {$class_name}.php could not be found.");
}
}
?>
//function.php
下面是content.php的部分内容
//content.php
<img src="<?php echo SITE_ROOT.DS.'images'.DS.'image1.jpg' ?>" />
//content.php
" />
下面是index.php:
//index.php
<?php require_once "includes/initialize.php";?>
<?php include_layout_template("index_header.php"); ?>
<?php include_layout_template("sidebar.php"); ?>
<?php include_layout_template("index_content.php"); ?>
<?php include_layout_template("footer.php"); ?>
//index.php
所以,我的问题是,content.php中的代码:
<img src="<?php echo SITE_ROOT.DS.'images'.DS.'image1.jpg' ?>" />
“/>
不起作用。因为文件无法识别SITE\u ROOT
和DS
常量。因此,SITE中没有图像。我知道,因为不包括initialize.php。在函数中没有包含。php但是DS
和SITE\u ROOT
起作用。虽然index.php中包含了initialize.php,但为什么包含的文件中没有这些站点根目录和DS
。如果我将
插入到includes文件夹中的文件中,则index.php中会有许多initialize.php
通过仅在一个文件中使用一个
,我如何解决此问题?或者更好的设计是什么。我强烈建议您看看PHP中的和。functions.PHP可以工作,因为它包含在initialize.PHP中,initialize.PHP包含所需的定义
content.php需要包含initialize.php。尽管index.php包含它,但content.php是一个不同的文件,不是调用链的一部分,并且是独立于index.php调用的,因此需要包含initialize.php
您需要将initialize.php作为公共包含文件包含在所有程序文件中
另一种方法是在index.php中包含content.php,然后content.php将能够自动访问initialize.php中的定义