Variables Scope in PHP

Variable scope in php

Table of Contents

In PHP, variables can have different scopes, and there are several types of variables based on their scope and behavior. The most common types are as given bellow.

Local Variables :

  • Local variables are declared inside a function and have local scope, meaning they are only accessible within that function.
  • They are not accessible from outside the function or in other functions.
  • Local variables are temporary and are destroyed when the function’s execution ends.
				
					function myFunction() {
    $localVar = "I am local";
    // $localVar is only accessible within myFunction
}
				
			

Global Variables :

  • Global variables are declared outside of any function and have global scope, meaning they are accessible from anywhere in the script, including inside functions.
  • To use a global variable inside a function, you need to use the global keyword to declare it as global within the function.
				
					function myFunction() {
    $localVar = "I am local";
    // $localVar is only accessible within myFunction
}
				
			

Static Variables :​

  • Static variables are local variables that retain their value between function calls.
  • They are declared with the static keyword inside a function and are initialized only once when the function is first called.
  • Static variables are useful when you want a variable to persist its value across multiple function calls.
				
					function counter() {
    static $count = 0;
    $count++;
    echo $count;
}
counter(); // Outputs: 1
counter(); // Outputs: 2

				
			

Superglobals :

  • Superglobals are predefined global arrays in PHP that are accessible from anywhere in the script without the need to declare them as global.
  • Some common superglobals include $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, and $_GLOBALS.
  • They are typically used to retrieve information such as form data, server information, or session data.
				
					$username = $_POST['username'];

				
			
Posted Under PHP

Leave a Reply

Your email address will not be published. Required fields are marked *