-4

I'm trying to access variables globally.

I created a file test1.php and in it I wrote

<?php
    $a = 5;
    $b = 7;
?>

And in another file test2.php I wrote,

<?php 
    global $a, $b;
    echo $a + $b;
?>

but result was 0.

So,

  1. Can't I use $a, $b in other page?
  2. Do I need to use session for this?
DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60
doflamingo
  • 567
  • 5
  • 23
  • only if you include the file. Right now, the left hand doesn't know what the right hand is doing. – Funk Forty Niner Dec 27 '16 at 03:41
  • 1
    if you don't `include` one script to the other you'd need to use `$_SESSION`, yes. Or pass it as parameter from one script to the other – Jeff Dec 27 '16 at 03:42
  • 1
    [Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) --- http://php.net/manual/en/language.variables.scope.php – Funk Forty Niner Dec 27 '16 at 03:44
  • *"So Could it be used in other page? or should I use session ?"* - That is entirely up to you. – Funk Forty Niner Dec 27 '16 at 03:45

1 Answers1

1

Better way is to introduce a file called globals.php and have all your variables there.

<?php
    $a = 5;
    $b = 7;
?>

Then in your test2.php file, include the globals.php. Then you can use your variables.

include "globals.php"
echo $a + $b;

The global keyword can be used if you are to use your variables inside a function, without passing them inside the function.

like,

include "globals.php"

function calculate(){
    global $a, $b;
    return $a + $b;
}

echo calculate();

If you are not going to use a file like globals.php, your option is to save the values in $_SESSION, which can be quite ugly when you have more stuff! But still can use.

Since you state that you are beginner, It is always good to keep stuff separate. Global variables separately, Functions separately, etc... and include them in the files that you are going to use them. This separation helps you to manage stuff easily when they grow. (ex: if it is a function that you want to debug into, you know where it is...)

Hope this helped you! Thanks.

masterFly
  • 1,072
  • 12
  • 24