PHP Variable Scope

The scope of a variable is defined as its range in the program under which it can be accessed. In other words, “The scope of a variable is the portion of the program within which it is defined and can be accessed.”

PHP has three types of variable scopes:

  1. Local variable
  2. Global variable
  3. Static variable

Local variable

The variables declared within a function are called local variables to that function and has its scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with same name as that of the one within the function is a complete different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements.

Ex.1

Output:

Local variable declared inside the function is: 50

Ex.2

Output:

Web development language: PHP
Notice: Undefined variable: lang in C:\xampp\htdocs\dkyadav\index.php on line 16

Global variable

The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.

Ex.1

Output:

Variable inside the function: Dharmendra Yadav
Variable outside the function: Dharmendra Yadav

Note: Without using the global keyword, if you try to access a global variable inside the function, it will generate an error that the variable is undefined.

Ex.2

Output:

Notice: Undefined variable: name in C:\xampp\htdocs\dkyadav\index.php on line 12
Variable inside the function:

Ex.3

Output:

Sum of global variables is: 18

If two variables, local and global, have the same name, then the local variable has higher priority than the global variable inside the function.

Ex.4

Output:

value of x: 7

Note: local variable has higher priority than the global variable.

Static variable

It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use static keyword and the variables are then called as static variables.  PHP associates a data type depending on the value for the variable.

Ex.1

Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

You have to notice that $x regularly increments after each function call, where as $y does not. This is why because $y is not a static variable, so it freed its memory after the execution of each function call.

Share on:

Free Exclusive Traffic Tips

Enter your email below to get access to my
proven SEO and traffic tips.

Hello, I am Dharmendra Yadav and I am a Blogger, Web Developer, Web Designer, Search Engine Optimizer, Digital Marketing Instructor. You can find me on Facebook , Linkedin

Leave a Comment