Passing a variable from one php include file to another: global vs. not Passing a variable from one php include file to another: global vs. not php php

Passing a variable from one php include file to another: global vs. not


The parent file has access to variables in both included files

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 front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc 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.

The included file doesn't have access to the other included 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.


Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.

include('front.inc');global $name;function foo() {  echo $name;}function bar() {  echo $name;}foo();bar();

will only show errors. The correct way to do that would be:

include('front.inc');function foo() {  global $name;  echo $name;}function bar() {  global $name;  echo $name;}foo();bar();


This is all you have to do:

In front.inc

global $name;$name = 'james';