Passing a variable from one php includes a file in another: global vs. not

I am trying to pass a variable from one include file to another. This does NOT work unless I declare the variable global in the second include file. However, I do not need to declare it global in the file that calls the first include. For example:




front.inc:

$name = 'james'; 



index.php:

 include('front.inc'); echo $name; include('end.inc'); 

output: james




end.inc:

 echo $name; 

conclusion: nothing




IF I declare a global name $ before repeating $ name in end.inc, then it works correctly. The accepted answer to this post explains that it depends on your server configuration: Passing variables in PHP from one file to another

I am using Apache server. How to configure it so that a global name declaration is not necessary? Are there any advantages / disadvantages for one and the other?

+60
variables scope include php global
Jan 13 2018-11-11T00:
source share
4 answers

When you include files in PHP, it acts like the code in the file from which they are included. Present a copy and paste of code from each of your included files directly into your index.php . Here's how PHP works with.

So, in your example, since you set a variable named $name in your front.inc file and then included both front.inc and end.inc in index.php , you can echo $name variable somewhere after include of front.inc inside your index.php . Again, PHP processes your index.php as if the code from the two files you include contains part of the file.

When you put echo inside the included file in a variable that is not defined internally, you will not get the result, because it is processed separately, and then any other included file.

In other words, in order to fulfill the behavior you expect, you will need to define it as global.

+50
Jan 13 2018-11-11T00:
source share

There is a trap here to avoid. If you need to access the $ name variable inside a function, you need to say "global $ name;" at the beginning of this 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(); 

only errors will be displayed. The correct way to do this is:

 include('front.inc'); function foo() { global $name; echo $name; } function bar() { global $name; echo $name; } foo(); bar(); 
+24
Sep 28 '11 at 11:22
source share

This is all you need to do:

In front.inc

 global $name; $name = 'james'; 
-2
Jan 18 '17 at 3:57
source share

I have a strange solution. in the end.inc file, add this line:

 $name=$name; 

Then the echo will work.

I got into this solution in my project, without a good explanation of why it works as follows.

-10
Aug 16 2018-12-12T00:
source share



All Articles