I read in some books related to PHP programming lenguage that in PHP the global variables don´t exist, instead, there are constant number that we can use anywhere in our script. But recently I learned that we can use global variables and in this article I will show you how to use them.
First of all, I want to show you how the variables inside a function live only inside the respective function. Analize the next lines of code:
<?php
function example(){
$number = 4;
}
$number = 30;
example();
echo "$number";
?>
Here we have a variable named number but the variable have been declared inside the function example and outside the function as well. So, at the moment to print the variable with the command echo
the result will be 30. Because the variable inside the function only lives inside the function where this was declarated.
Well, now pay attention to the next lines of code:
<?php
function example(){
global $number;
$number = 4;
}
$number = 30;
example();
echo "$number";
?>
In this case the result will be 4 because the variable is global, but for example, let’s see the following example:
<?php
function example(){
global $number;
$number = 4;
}
$number = 30;
example();
$number = 10;
echo "$number";
?>
In this case the result will be 10, because we change the variable before to print it wit the echo command.