Question

I'm creating my own Templating Script by using the ob_get_contents() as a core method. By using it, it can render out the other files, calling from the one single file.

Just like, lets assume we have 4 files:

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

index.php will call and render the contents of other files (2 html files here). By using the following codes:

//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');

But (for example) when header.html contains a call include('functions.php'), the included file (functions.php) can't be used again in footer.html. I mean, i have to make a include again in footer.html. So here, the line include('functions.php') have to be containing in both of files.

How to include() a file without calling it again from child files?

Was it helpful?

Solution

When you use ob_start() (Output buffering), you end up only with the output of the file, meaning file executed the output is returned by ob_get_content(). As only output is returned that other file is unaware of the includes.

So the answer is: you can't do it with output buffering. Or include your files before ob_start with include_once.

OTHER TIPS

That could work like something like this:

//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');

Alternatively you could use include_once (include_once $file;)and PHP will do it for you.

Though I suggest you just make sure the file loading structure is in such shape that these events never happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top