86

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:


front.inc:

$name = 'james';

index.php:

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

output: james


end.inc:

echo $name;

output: nothing


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?

Community
  • 1
  • 1
maxedison
  • 17,243
  • 14
  • 67
  • 114
  • 2
    includes are not like functions. includes do not break the variable scope. it's as if you copy pasted the include files contents directly into the calling script. – dqhendricks Jan 13 '11 at 01:32
  • 2
    is the echo in end.inc within a function? – dqhendricks Jan 13 '11 at 01:32
  • 2
    that would break the variable scope. and in that case you should probably pass $name to the function in an argument. – dqhendricks Jan 13 '11 at 01:34
  • This *should* work as written! – deceze Jan 13 '11 at 01:36
  • the echo in end.inc is not inside a function. Assume that the three files I described above contain no more and no less than exactly what I wrote. – maxedison Jan 14 '11 at 21:01
  • This works now as intented. At least for me with XAMPP and PHP 5.6. It must have been an error of earlier php versions then?? – NoDataDumpNoContribution Mar 08 '15 at 20:17
  • I am playing with it again even I have written below comment about that I had the same problem. More precisely I had this problem on large existing web, but when I create only simple three *.php files like maxedison described I don't have this problem and echo from end.inc displays value of $name. Maybe it is depending on some used PHP calls in web initialization ? Maxedison tolds something about server configuration which can be reason of this problem. I looked into attached link, but did not find anything about server configuration. Can somebody bring more light on this problem ? – StackPeter Feb 20 '17 at 13:27

5 Answers5

74

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.

Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
  • 56
    Your response seems to contradict itself. You said a couple times that including a file is the same as if all the code was simply part of one file. Therefore, what I described in my post would be equivalent to: $name = 'james'; echo $name; echo $name; -- That should produce jamesjames. But your second-to-last paragraph contradicts what I just described. Perhaps what you mean is that ONLY the file making the include call has access to the included file's variables, so other included files do NOT have access to those variables. Is that correct? – maxedison Jan 14 '11 at 21:00
  • 26
    Yeah, that sounds correct. Sorry if I what I said was confusing. I edited it like 5 times because I was having a really hard to describing the process without getting you lost. So, the parent file has access to variables in both included files, but the included file doesn't have access to the other included file. If that makes any sense. – Michael Irigoyen Jan 14 '11 at 21:10
  • As well as the accepted answer, its correction is also wrong (or outdated). In PHP7 (at least) I can define a variable in `included1.php` and reference it later in `included2.php` without referencing it in `parent.php`, and get the the value I defined in `included1.php`. I follow the same scope rules that I would if the code was all on a single page. Nothing more. – biscuitstack Sep 04 '18 at 17:47
  • 5
    Voted down because the first two paragraphs contradict the following sentence explicitly. – Muckee Dec 10 '18 at 07:31
  • In short: throw your included file in to a function and pass the needed variables as parameters. It's obnoxious but it works. ︀ – John Sep 16 '20 at 21:01
  • I like this sentence **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.** I discovered this when I was learning PHP. Then I see this to make it even clear that what I thought was right. THanks! – Ice Bear Mar 15 '21 at 08:10
  • 1
    @JoshuaFlood I've add parts of the [author's comment](https://stackoverflow.com/questions/4675932/passing-a-variable-from-one-php-include-file-to-another-global-vs-not#comment5181093_4676007) as headers for the two parts of the answer to make the answer clearer and to avoid confusion when reading it. – Gleb Kemarsky Aug 30 '21 at 07:19
  • 1
    Changed to an upvote @GlebKemarsky – Muckee Oct 13 '21 at 12:13
36

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();
Kağan Kayal
  • 2,303
  • 1
  • 19
  • 30
2

Same here with php 5.4.7

$mysql = false;
include("inc_mysql.php");
echo($mysql);

Where inc_mysql.php:

$mysql = true;

Echoes a value of $mysql = false;

BUT

if you remove the first $mysql=false;

include("inc_mysql.php");
echo($mysql);

Echoes a value of $mysql = true;

SO definitively, doing an include IS NOT like copying/pasting code, at least, in some PHP versions.

Pau
  • 31
  • 2
1

This is all you have to do:

In front.inc

global $name;
$name = 'james';
Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
  • 2
    Add some explanation with answer for how this answer help OP in fixing current issue – ρяσѕρєя K Jan 18 '17 at 04:31
  • 1
    I had the same problem like described by maxedison. I was also confused with many answers: "php process includes like you copy and paste..." which is not true and thanks to Michael's explanation under his answer I understand that code in included file does not recognize global variable defined in previous include file. In my experiments I also met that if I use "global" keyword in first iclude can correct this - like answered Paul. But where can I find both cases described in PHP documentation ? And second question is if both are not true only from some PHP version ? – StackPeter Feb 20 '17 at 11:19
1

It's all about scope. It seems that in PHP the variables defined in the global scope are not automatically inherited in the function's scope. That's why, within a function body, you have to prepend the variable with the global keyword.

From the PHP manual:

A true global variable imported inside a function scope with the global statement actually creates a reference to the global variable.

So the variable $name is available to both includes (front.inc and end.inc ) but any function defined in those files would not have access to variable $name unless the global keyword is used or the $GLOBALS constant.

I've grabbed some code from https://www.php.net/manual/en/language.variables.scope.php to better understand this issue:

<?php
$a = 1; /* global scope */ 

function test()
{
    /* the code below will throw a Warning: Undefined variable $a ... */
    echo $a; /* reference to local scope variable */
} 

To get the variable value you'll have to call global $a like this:

<?php
$a = 2; /* global scope */

function test2() {
    global $a;
    /* now we have access to the global $a so no more warnings */
    echo $a;
}

You can also rely on $GLOBALS to get access to the global like this:

<?php
$a = 3; /* global scope */

function test3() {
    echo $GLOBALS['a'];
}

You can get a list of all global variables with a code like this:

echo "<pre>";
print_r($GLOBALS);
echo "</pre>";

Source for code above: Is it possible to List Out All the Global variables in PHP?

Ciprian Tepes
  • 806
  • 9
  • 11