View Full Version : Declaring a variable before it is set..... output buffering??

01-30-2012, 11:57 AM
I want to use a variable in the <title></title> to display the name of the article being shown on the page.

Each page uses an included header and footer file, and output buffering is being used.

So each page starts like this..

$page_title = "Page Title";
include 'header.php';
include 'footer.php';

...and header.php echos out the $page_title in the title tag.

However I want the $page_title varible to reflect the actual name of the article, which is set dynamically in the $article_title variable further down the page. Something like..

$page_title = $article_title;
include 'header.php';
$article_title = $result['title'];
include 'footer.php';

But of course due to the way I'm including the header this needs to be put before the variable is actually set causing the problem.

I already use output buffering, is there a way i can use this to help? This has to be quite a common problem I think...

Thanks in advance! This has been a problem to me for a while and I can't figure out the best way around it!!

01-30-2012, 12:12 PM
You should really look into seperating out the various parts of your site. Think along the lines of a template (without using a templating system) for the main design. Seperate each page into 2 sections, a model and a view. Execute the model before you display anything. It will parse all the incoming data and prepare the data to be displayed. Then as you're displaying the main template, include the view for the current page wherever your template holds the output of the page.

This allows you to set the title in the model. Which solves the chicken before the egg problem ;)
See http://www.codingforums.com/showthread.php?t=129123

01-30-2012, 01:24 PM
Output buffering simply stops headers being sent. It doesn't allow you to change what has already been printed to the HTML - as far as I know anyway.

What you need to do, is seperate your html and PHP. Run the php FIRST and then put all the generated content into the html.

01-30-2012, 01:40 PM
post the contents of your header.php file here... there will be a way for it to work..