Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP global variables across files

Tags:

php

global

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?

like image 979
riwalk Avatar asked Feb 02 '11 00:02

riwalk


2 Answers

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.

like image 96
fiiv Avatar answered Sep 21 '22 06:09

fiiv


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...

like image 26
Doc Avatar answered Sep 19 '22 06:09

Doc