Using variables before including () them

I am using a file, page.php, as an HTML container for multiple content files; that is, page.php defines most of the overall structure of the page, and content files simply contain text that is unique to each page. What I would like to do is include some PHP code with each content file that defines the metadata for the page, such as its title, image banner to use, etc. For example, a content file might look like this (simplified):

<?php $page_title="My Title"; ?>
<h1>Hello world!</h1>

      

The filename will be passed as a URL parameter to page.php, which will look like this:

<html>
  <head>
    <title><?php echo $page_title; ?></title>
  </head>
  <body>
    <?php include($_GET['page']); ?>
  </body>
</html>

      

The problem with this approach is that the variable is defined after using it, which of course will not work. Output buffering doesn't help either.

Is there an alternative approach that I can use? I would rather not define the text in the content file as a PHP heredoc block, because that breaks the HTML syntax highlighting in my text editor. I also don't want to use JavaScript to rewrite page elements after the fact, because many of these pages don't use JavaScript, and I would rather not inject it as a dependency if I don't need to.

+2


a source to share


2 answers


Most users save the output of the included page to another variable. Have you tried putting all the contents of the included page in the output buffer and then storing it ob_get_clean()

in a variable like this $page_html

, after which your page would look like this:

<?php include($_GET['page']); ?>
<html>
  <head>
    <title><?php echo $page_title; ?></title>
  </head>
  <body>
    <?php echo $page_html; ?>
  </body>
</html>

      



Edit: So the second page would look something like this:

<?php
$page_title="My Title";
ob_start();
?>
<h1>Hello world!</h1>
<?php $page_html=ob_get_clean(); ?>

      

+2


a source


The best I can think of is decoupling the file inclusion from the rendering. Therefore your template looks like this:

<?php include($_GET['page']); ?>
<html>
  <head>
    <title><?php echo $page_title; ?></title>
  </head>
  <body>
     <?php renderPage() ?>
  </body>
</html>

      

And the file you include looks like this:



<?php
$page_title="My Title";
function renderPage() {
?>
<h1>Hello world!</h1>
<?php 
}
?>

      

It's also good, as you can pass parameters to renderPage () so that the template can pass information along with the page it belongs to.

+1


a source







All Articles