PHP global variables across files

2019-02-23 12:58发布

问题:

Ok, maybe my brain is just shut off, but I can't get this to work.

Here's the complete code:

Page1.php:

<?php
    $something = "hello";
    include "Page2.php";
?>

Page2.php:

<?php
    echo $something;
?>

Desired output (when navigating to Page1.php):

hello

The real output is blank. I have tried putting the global keyword everywhere, and nothing happens. Am I missing something?

回答1:

I cannot replicate this error, just tried this on my localhost and copied and pasted your code from here. I suspect you have some sort of syntax error.

Turn on error reports and see if you get any errors.



回答2:

I know this is a late answer, but I'm trying to do something similar. First of all, when you echo something you still have to put it in " ". Php will recognize it as a variable as long as you put the $.

Second, you're including page2.php in page1. Fantastic, but page2 does not recognize $something. Now, if you do it the other way, declare $something in page2, and then call it from page 1 after including it, it will run.

Modifying the variable would require something else...



回答3:

I think the output is coming in page2.php . Am i right? this is because you are echoing a unset variable in page2.php you need to change the following data in order to make it work. page1.php

<?php
include("page2.php");
echo $something;
?>

page2.php

<?php
$something="Hello";
?>

If you will use it and navigate the page 1.php then the output will be Hello



回答4:

I had a similar problem running on local (Windows) where the values of an array did not follow past the include within the same process.

After switching the include path from http://localhost/www/example.php to C:/www/example.php, it works fine now.



标签: php global