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'); ?>
Share

One Response to ' PHP: Access A Variable from an Include File '

Subscribe to comments with RSS or TrackBack to ' PHP: Access A Variable from an Include File '.

  1. Tim said,

    on February 5th, 2009 at 4:09 am

    I had same problem …
    also solved it with variable define as global
    but what to do when GLOBALS array is disabled at php.ini

    mean what solution can be except global use?
    thanks

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word