如何处理 php 中不同文件的“分离包含”


How to handle with "separate including" from different files in php?

一个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

我的初始化.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');
?>

这是功能.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.");
   }
}
?>

以下是部分内容.php

//content.php
 <img src="<?php echo SITE_ROOT.DS.'images'.DS.'image1.jpg' ?>" />

这是索引.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"); ?>

所以,我的问题是,内容中的代码.php:

<img src="<?php echo SITE_ROOT.DS.'images'.DS.'image1.jpg' ?>" />

不行。因为该文件无法识别SITE_ROOTDS常量。因此,站点中没有图像。我知道,因为不包括初始化.php。功能中没有包含.phpDSSITE_ROOT有效。虽然 initialify.php 包含在 index.php 中,为什么包含下的文件看不到这些SITE_ROOTDS。如果我将<?php require_once "includes/initialize.php";?>插入到包含文件夹中的文件,则会有很多初始化.php在index.php中。

通过仅在一个文件中使用一个<?php require_once "includes/initialize.php";?>,如何解决此问题?或者如何更好的设计。

我强烈建议您看看 PHP 中的 OOP 和自动加载。

函数.php之所以有效,是因为它包含在 initialize 中.php其中包含所需的定义。

内容.php需要包括初始化.php。虽然 index.php 包含它,但内容.php是一个不同的文件,不是调用链的一部分,并且独立于 index 进行调用.php因此需要包含 initialize.php。

您需要在所有程序文件中包含 initialify.php 作为公共包含文件。

另一种出路是将内容包含在索引中.php.php然后内容.php将能够自动访问初始化中的定义.php。