PHP global variables across files

2019-02-23 13:03发布

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?

标签: php global
4条回答
对你真心纯属浪费
2楼-- · 2019-02-23 13:40

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楼-- · 2019-02-23 13:45

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

查看更多
forever°为你锁心
4楼-- · 2019-02-23 14:01

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.

查看更多
时光不老,我们不散
5楼-- · 2019-02-23 14:02

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.

查看更多
登录 后发表回答