Viewed   1.3k times

I'm trying to pass a variable from one include file to another. This is NOT working unless I declare the variable as global in the second include file. However, I do NOT need to declare it as global in the file that is calling the first include. For example:

$name = 'james';


echo $name;

output: james

echo $name;

output: nothing

IF I declare global $name prior to echoing $name in, then it works properly. The accepted answer to this post explains that this depends on your server configuration: Passing variables in PHP from one file to another

I'm using an Apache server. How would I configure it so that declaring $name to be global is not necessary? Are there advantages/disadvantages to one vs. the other?



When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your file, and then included both and in your index.php, you will be able to echo the variable $name anywhere after the include of within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

Friday, August 12, 2022

You can store the variables in the session.

Tuesday, October 25, 2022

Change it

 $image = '$_GET[image_url]'; 


 $image = $_GET['image']; 
Sunday, November 20, 2022

Variables do propagate to the included files, so it must be, that the variable is NOT set when you call the include: try checking if so, then figure out why is the variable not set at that point.

For example, if you defined $logged inside the "if" block or inside a function, then it won't propagate outside of it: you must define it in the outermost scope (at the same level at which you call the include statement). And you must define it for the case that the user is not logged in, not only for the case when the user is logged in. If the variable is not initialized to false, the check if(!$logged) will issue warning. Say $logged = false; at the beginning of your work.

Friday, October 7, 2022

They should just roll over:


$var1 = "TEST";


echo $var1; //Outputs TEST
Friday, August 5, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :