php-variable-scope

PHP Variable Scope


Variable Scope is an accessible area / portion for any variable where a variable can be accessed after it has been defined.

There are mainly three types of variables Scopes:

  • Local Variable
  • Global Variable
  • Static Variable
  • Local variable: Local Variables are those variables that are define inside a function and are accessible within the same function, and can’t be accessed that variable outside that function.   
  • Example :

Output: Variable inside the function.

 

  • Global variable: You can use Global keyword inside a function to access global variables. Before using variables, add global keyword followed by comma-separated variable names you need to use inside the function.    
  • Example -

OUTPUT: Hello internet

 

  • Static variable: Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
  •  use the static keyword when you first declare the variable.

  • Example:

Output:  0
         1
         2

 

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

  • The variable is still local to the function.