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';
include('front.inc'); echo $name; include('end.inc');
IF I declare global $name prior to echoing $name in end.inc, 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
front.incfile, and then included both
index.php, you will be able to
$nameanywhere after the
index.php. Again, PHP processes your
index.phpas if the code from the two files you are including are part of the file.
When you place an
echowithin 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.