2012-07-12 87 views
3

我遇到了嵌套包含問題。雖然我看到有一些類似的問題,但他們似乎沒有幫助。嵌套包括在PHP中

通常我沒有包括問題,但最近我一直在嘗試新的東西,我無法讓嵌套包括工作。

一種解決方案:php nested include behavior

基本設置:

  • 的index.php包括 '/include/header.php'
  • 的header.php包括 '/resources/login/index_alt.php'
  • index_alt.php包括 '/resources/login/index_auth.php'
  • index_auth.php包括 '/class/Login.class.php' 和 「/class/Connection.class/ php'

我實際上沒有寫這樣的路徑(它理解深度)。 這是它在頁面上的顯示方式。

的index.php

  • 包括( '包括/ header.php文件');

的header.php:(報頭被包括在除了/資源每深度級別/ ...)

  • 包括( '../資源/登錄/ index_alt.php') ;

index_alt.php

  • 包括( 'index_auth.php');

index_auth.php

  • 包括( '../../類/ Login.class.php');
  • include('../../ class/Connection.class.php');

在頭文件被接受,一些深層次,但包括嵌套在不會...

+1

我建議你重新考慮你的包括戰略,包括其本身包括文件,這反過來也可以包括文件只能帶來麻煩,從長遠來看的依賴性越來越糊塗文件。你最好一次性完成所有包含,即直接訪問的腳本。更好的是,如果你使用面向對象的方法,你可以使用自動加載器。 – GordonM 2012-07-12 18:41:21

+0

看看include_once()或require_once()。這樣您就不必擔心多次包含單個文件。 – Jim 2012-07-12 18:46:37

+0

@GordonM感謝您的評論。它並不像你想象的那麼糟糕。有了這個額外的功能,我需要其他地方已經實現的代碼。 – TaserPain 2012-07-12 19:25:42

回答

4

假設文件系統看起來像這樣..

/www 
    include/header.php 
    class/Login.class.php 
    class/Connection.class.php 
    resources/login/index_alt.php 
    resources/login/index_auth.php 
    index.php 

這意味着

index.php: include(__DIR__ . '/include/header.php'); 
header.php: include(__DIR__ . '/../resources/login/index_alt.php'); 
index_alt.php: include(__DIR__ . '/index_auth.php'); 

等;看到http://php.net/manual/en/language.constants.predefined.php

2

而是向上遍歷目錄樹與../使用目錄名(__FILE__)的。此外,你可能想include_once()的或require_once(),以避免其他潛在問題:

的index.php:

include('include/header.php'); 

頭。PHP:

include(dirname(dirname(__FILE__)) . '/resources/login/index_alt.php'); 

(請注意,目錄名(__FILE__)將返回當前目錄,目錄名,但(目錄名(__FILE__))將返回母)