PHP Variable Scope and Working Capability

Variable scope means to work in a position where it has the capability to do that. During coding, we have to declare several types of variable. They can be used in different places according to their rights. That means when we declare a variable publicly then it can be used anywhere in the program. But a variable that is declared inside a function can’t be used outside of the function.

A variable that is declared inside a function is known as local variable and variable which is declared outside of a function is known as the global variable. Local variable can’t be used in other places whereas global variable has that capability. We can see an example from below for test function.

In this program, $p is in outside and $q is inside of the function. We can easily print the value of $p. But if we want to print the value of $q then it will generate an error like below which is an undefined index with line number.

This means that variable $q can’t be used outside the function. But $p will easily give answer 50 as output.

It will be better if you try with different variables to find out such kind of errors.

 

Share This on Social Media