2012-05-16 59 views
0

A index.php文件有許多包括文件,並且在其中一些包括文件中,有一些變量屬於包含index.php的文件。我只能將index.php文件寫入「包含代碼」或將「包含代碼」插入所有單獨的文件index.php文件包含在內?這可能是很難理解我寫的可能,但這裏是我的文件夾和編碼:如何處理「單獨包含」從不同的文件在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'); 

?> 

這裏是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."); 
    } 
} 
?> 

這裏是content.php

的某些部分
//content.php 

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

這裏是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"); ?> 

所以,我的問題是,該代碼在content.php:

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

不起作用。由於該文件不識別SITE_ROOTDS常量。因此,網站中沒有圖像。我知道,因爲initialize.php不包括在內。沒有包括在function.phpDSSITE_ROOT的作品。雖然initialize.php包含在index.php中,爲什麼下的文件包含沒有看到這些SITE_ROOTDS。如果我將<?php require_once "includes/initialize.php";?>插入到includes文件夾中的文件中,那麼index.php中會有很多initialize.php。

通過在一個文件中只使用一個<?php require_once "includes/initialize.php";?>,我該如何解決這個問題?或者如何更好的設計。

回答

0

functions.php的工作原理是它包含在initialize.php中,它包含了所需的定義。

content.php需要包含initialize.php。雖然index.php包含它,但content.php是一個不同的文件,不是調用鏈的一部分,並且獨立於index.php調用,因此需要包含initialize.php。

您需要在所有程序文件中包含initialize.php作爲常用包含文件。

另一個出路是將content.php包含在index.php中,然後content.php將能夠自動訪問initialize.php中的定義。

相關問題