Variable scope refers to the visibility of a variable inside the source code. In other words, variable scope denotes a boundary in which a variable is visible or accessed. Basically, it defines which part of the code uses that variable. To learn variable scope, you must be aware of function.
There are three types of variable scope in
A variable declared inside the function has local scope. It means these variables can only access inside the function. These variables can not be accessed outside of the function because they have local scope.
Please keep in mind that a variable declared outside of the function with the same name is completely different from the variable that is declared inside the function.
A variable declared outside of the function has a global scope and it will be accessed outside of the function but it can not be accessed inside the function.
To access global variables inside the function,
PHP provides two methods that are used to access global variables inside the function. These two methods are:
To access the global variables inside the function, use the global keyword before the variables.
Let us understand it with the help of an example.
PHP provides another way to access the global variable through the
$GLOBALS array. Please keep in mind that the
$GLOBALS array is saved for all the global variables. The array key contains the variable name. The array value contains the variable value.
Please keep in mind that after the execution of the function all the variables are deleted but sometimes we have a requirement of the local variable for the next job.
So to this, use the static keyword before the variable name inside the function and perform your next job..