ob_get_contents()
をコアメソッドとして使用して、独自のテンプレートスクリプトを作成しています。これを使用することで、1つのファイルから呼び出して他のファイルをレンダリングできます。
同様に、4つのファイルがあると仮定します。
- index.php
- header.html
- footer.html
- 関数.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()
子ファイルから再度呼び出さずにファイルを作成するにはどうすればよいですか?