Can you explain the three scopes of variables in PHP and how they differ from each other?

In PHP, variables have three main scopes, which determine where they can be accessed and manipulated within a script. These scopes are:

  1. Global Scope: Variables declared outside of any function or class have global scope. They can be accessed from anywhere within the script, including inside functions, methods, and classes. Global variables are defined using the global keyword or by simply declaring them outside of any function or class. However, modifying global variables from within functions can lead to code that is harder to maintain and debug, as it increases the risk of unintended side effects.

     phpCopy code$globalVariable = 10;
    
     function myFunction() {
         global $globalVariable;
         echo $globalVariable; // Output: 10
     }
    
     myFunction();
    
  2. Local Scope: Variables declared inside a function or method have local scope. They can only be accessed within the function or method in which they are defined. Local variables are created when the function or method is called and destroyed when it completes execution. They are isolated from variables with the same name in other scopes.

     phpCopy codefunction myFunction() {
         $localVariable = 20;
         echo $localVariable; // Output: 20
     }
    
     myFunction();
    
  3. Static Scope: Static variables are a special type of local variable that retains its value between function calls. They are declared using the static keyword inside a function or method. Static variables are initialized only once when the function is first called, and their value persists across subsequent calls to the function.

     phpCopy codefunction myFunction() {
         static $staticVariable = 30;
         echo $staticVariable; // Output: 30
         $staticVariable++;
     }
    
     myFunction(); // Output: 30
     myFunction(); // Output: 31
     myFunction(); // Output: 32
    

In summary, the main differences between the three scopes of variables in PHP are:

  • Global variables can be accessed from anywhere within the script.

  • Local variables are limited to the function or method in which they are defined.

  • Static variables retain their value between function calls and are shared across multiple invocations of the function.