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.