PHP Variable Scope Concept

PHP | Variable Scope

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 PHP namely:

      1.0 Local Scope
      2.0 Global Scope
      3.0 Static Scope

Local variable

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.

Source Code

Try it now

Global Scope

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.

Source Code

Try it now

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:

      1.0 Using The global Keyword
      2.0 Using The $GLOBALS Array

PHP global Keyword

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.

Source Code

Try it now

PHP $GLOBALS Array

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.

Source Code

Try it now

PHP Static Scope

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..

Source Code

Try it now