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