June 7th, 2006

PHP: Access A Variable from an Include File

Recently I ran into a problem with include files. I had a header file which was included in every page, and had a default title. However, in any page calling the header, I wanted to be able to over-write the title, and then display the header.

My header.php file looked like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><?php echo $title; ?>My default site title</title>
<link href="/styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>

And the index.php like this:

<?php $title = "home - "; ?>
<?php include('./header.php'); ?>

However, the "home - " never showed up, only the default title. I realized it had to do with the variable scope. It was really just a matter of calling the $title variable as global, like this:

<?php global $title ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><?php echo $title; ?>My default site title</title>
<link href="/styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>

And the index.php like this:

<?php
 global $title;
 $title = "home - "; ?>
<?php include('./header.php'); ?>

Leave a reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image