2012-03-21 50 views
1

我使用ob_get_contents()作爲核心方法創建自己的模板腳本。通過使用它,它可以渲染出其他文件,從單個文件調用。(PHP)如何將之前的INCLUDE/REQUIRE調用傳遞給子文件?

就像,讓我們假設我們有4個文件:

  • 的index.php
  • 了header.html
  • footer.html
  • 的functions.php

index.php將調用並呈現其他文件的內容(這裏是2個html文件)。通過下面的代碼:

//index.php 
function render($file) { 
    if (file_exists($file)) { 
    ob_start(); 
    include($file); 
    $content = ob_get_contents(); 
    ob_end_clean(); 
    return $content; 
    } 
} 
echo render('header.html'); 
echo render('footer.html'); 

但(例如)當header.html包含一呼叫include('functions.php'),包含的文件(functions.php中)不能在footer.html再次使用。我的意思是,我必須在footer.html中再次進行包含。所以在這裏,include('functions.php')必須包含在這兩個文件中。

如何將include()文件從子文件中再次調用

回答

1

當您使用ob_start()(輸出緩衝)時,您只會以文件的輸出結束,也就是說執行輸出的文件將返回ob_get_content()。由於只有輸出返回,其他文件不知道包含。

所以答案是:你不能用輸出緩衝來做到這一點。或者include ob_start之前的文件與include_once

+0

在'ob_start'之前包含我的文件和'include_once'?哦,對我的例子來說,如果我在'index.php'的頂部用'include_once'聲明瞭所有必要的文件,這是可能的。那麼孩子們不需要再次申報? – 2012-03-21 23:20:29

+1

@ 4lvin是的,當然這是可能的。您可以在開始時使用'include_once'或'require_once',並且您的所有子文件都將看到包含的內容。 – 2012-03-21 23:22:17

+0

噢!是啊!這是簡單的和令人難以置信的!乾杯和感謝阿爾曼體育 – 2012-03-21 23:34:02

1

可以工作像這樣的事情:

//index.php 
function render($file) { 
    if(!isset($GLOBALS['included'])) { 
     $GLOBALS['included'] = array(); 
    } 

    if (!in_array($file, $GLOBALS['included']) && file_exists($file)) { 
     ob_start(); 
     include($file); 
     $content = ob_get_contents(); 
     ob_end_clean(); 

     $GLOBALS['included'][] = $file; 
     return $content; 
    } 
} 

echo render('header.html'); 
echo render('footer.html'); 

另外,您可以使用include_onceinclude_once $file;)和PHP會爲你做它。

雖然我建議你只是確保文件加載結構是這樣的形狀,這些事件永遠不會發生。

+0

我可以只聲明'include_once'一次,在'index.php'文件的最頂部(在渲染子文件之前),而不是使用'$ GLOBALS'的方式嗎?請知道。 – 2012-03-21 23:26:06

+0

是的,你可以。但更好的是確保一個文件永遠不會被包含兩次,而不管被稱爲什麼文件。 – sg3s 2012-03-21 23:28:31

相關問題