Jake Lee
Jake Lee

Reputation: 7979

Trouble defining a variable in PHP?

Alright, so a content page uses this:

$tab = "Friends";
$title = "User Profile"; 
include '(the header file, with nav)';

And the header page has the code:

if ($tab == "Friends") { 
echo '<li id="current">'; 
} else { 
echo '<li>'; 
}

The problem is, that the if $tab == Friends condition is never activated, and no other variables are carried from the the content page, to the header page.

Does anyone know what I'm doing wrong?

Update: Alright, the problem seemed to disappear when I used ../scripts/filename.php, and only occurred when I used a full URL?

Any ideas why?

Upvotes: 0

Views: 104

Answers (3)

cHao
cHao

Reputation: 86506

When you include a full URL, you're not including the PHP script -- you're including the HTML it generates. It's just like you went to http://wherever.your.url.goes, but it's done by the server instead of the browser. The script runs in a whole separate process, caused by a separate request from the server to itself, and none of the $variables are shared between the two.

Short version: When you include http://wherever.your.url.goes, $tab will always be blank. If you include the actual file name, the variable will be shared.

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157839

  1. Now you see why it's awful practice to post some stubs and skeches instead of the real code

  2. Try to think, Your question is not a rocket science. Include is like copy-pasting code in place of include operator. Go load your inclided URL in browser, copy resulting code and paste it into your first file and see.

Upvotes: 1

Sander Marechal
Sander Marechal

Reputation: 23216

Your code as posted should work. How are you actually including that file? Does that happen inside a function? Then you need to use the global statement for it to work. Example:

File 1:

function my_include($file) {
    global $tab; // <-- add this
    include '/some/path/' . $file;
}

$tab = 'Friends';
my_inlcude('file_2.php');

File 2:

if ($tab == 'Friends') { ... }

Upvotes: 1

Related Questions