The way how we can know or we can access to the global variables is with a build-in array in PHP named $GLOBALS where there are all the global variables that come with a key and a value.

I will show you a few examples in order that you can be familiar with this “special” array.

Analize the next example:

<html><head><title>This is a sample</title></head><body><?php
                        $carModel = "Tesla";

                                $carModel = "Nio";

                                echo"The current \$carModel variable is $carModel \n\t\t";
                                echo"The global \$carModel variable is ".$GLOBALS["carModel"];


First of all, we can notice that the php script is embedded in a html file, I did this in that way because the code is small and is manageable to keep it within a html file.

The important thing to notice is that we have two variables with the same name; carModel but one variable is inside the function example and the other can be considered as a global variable. We can access to the global variable with the array previosly mentioned ($GLOBALS).

The main advantage here is that we don´t need to use the global prefix before to declarate a global variable and as well, we can access to any global variable in a easy way.

Escribe tu comentario
+ 2