PDA

View Full Version : Accessing variables within includes?



J_S
February 20th, 2007, 06:44 AM
I'm quite new to PHP and need some help. I've got index.php which looks like this:



<?php
$sectionname = "index";
include "header.php";
?>
Then in header.php i've got:


<?php
echo($sectionname);
?>
index.php displays blank (ie doesn't echo $sectionname). How can i make a variable defined in index.php available in header.php?

evildrummer
February 20th, 2007, 06:55 AM
What version of PHP are you running?

mlk
February 20th, 2007, 08:14 AM
works on my server... I've never seen code which needed to pass variables to includes though...

J_S
February 20th, 2007, 08:44 AM
I've got to the bottom of it. Before declaring $sectionname, I was using the 'require' function to load in a separate file with other variables defined. In there, is a 'switch' function and 'define' function, and the variable was defined before the 'switch' function. Once I put the 'switch' function before the 'define' function, my $sectionname variable became accessible in header.php.

Oh and mlk, I needed to send the variable to header.php so my navigation menu's buttons could change CSS style depending on what the current $sectionname (this variable basically says what page the user is viewing) was, like this:


<li <?php if ($sectionname == "index"){ echo("class=\"active\"");}?>><a href="index.php">Home</a></li>

Thanks for all your help guys.

bwh2
February 20th, 2007, 11:04 AM
if index.php includes header.php, any variables defined before the include will be accessible.


/**** index.php ****/

$foo = 'bar'; // accessible to header.php

include( 'header.php' );

$nope = 'not today'; // not accessible to header.php

bwh2
February 20th, 2007, 12:58 PM
you have an extra ) after $i]. it's cutting off your if statement prematurely.

J_S
February 20th, 2007, 01:01 PM
Yes just saw that myself and deleted my question as soon as I noticed. It's been a very long day - too much PHP my eyes are going funny!