简体   繁体   中英

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?

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 $variable s 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.

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') { ... }
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM