PHP Global Variables

Global Variables

Global variables are variables which are defined outside of a function, but are redecalred inside the function with a global keyword. The code below shows how $var1 uses the global keyword. When you use the global keyword, the variable takes on its original value. In this case, using global $var1 inside a function makes $var1 equal to the string “Hello”.

$var1 = "Hello";
$var2 = "World";
$var3 = "Variable 3 is outside function";

function myglobal_vars() {
global $var1; //$var1 has global scope
$var3 = "Hi this is var3 inside the function.";

echo $var1." ".$var2." from inside the function"; //$var2 has no global scope and will not output
echo "<br/><br/>";
echo $var3;
echo "<br/><br/><hr>";

echo "Only variable ".$var1." can be used inside and outside the function.";

echo "<br/><br/>".$var3; //different output than inside the function