Sobes.tech
Junior

What are the scope areas in PHP?

sobes.tech AI

Answer from AI

In PHP, the following scopes exist:

  1. Local: Variables declared inside a function. Accessible only within that function. The variable's lifetime is until the function executes.

    // Local scope
    function myFunc() {
        $localVar = "Visible only here";
        echo $localVar;
    }
    myFunc();
    // echo $localVar; // Error! Variable does not exist in the global scope
    
  2. Global: Variables declared outside functions. Accessible in the global namespace. Inside functions, to access them, use the global keyword or the $GLOBALS superglobal array.

    // Global scope
    $globalVar = "Visible everywhere";
    
    function anotherFunc() {
        global $globalVar; // Access to global variable
        echo $globalVar;
    }
    anotherFunc();
    echo $globalVar; // Access to global variable
    
  3. Static: Variables declared inside a function with the static keyword. They retain their value between function calls but are only accessible within that function (similar to local, but with state preservation).

    // Static scope
    function countingFunc() {
        static $staticVar = 0; // Initialized only on the first call
        $staticVar++;
        echo $staticVar;
    }
    
    countingFunc(); // Outputs 1
    countingFunc(); // Outputs 2
    countingFunc(); // Outputs 3
    
  4. Class/Object Scope: Variables (properties) and functions (methods) inside a class. Access depends on access modifiers (public, protected, private).

    • public: Accessible from everywhere (inside class, outside, from subclasses).
    • protected: Accessible inside the class and subclasses.
    • private: Accessible only within the class where declared.
    // Class/Object scope
    class MyClass {
        public $publicProperty = "Public";
        protected $protectedProperty = "Protected";
        private $privateProperty = "Private";
    
        public function showProperties() {
            echo $this->publicProperty;
            echo $this->protectedProperty;
            echo $this->privateProperty;
        }
    }
    
    $obj = new MyClass();
    echo $obj->publicProperty; // Accessible
    // echo $obj->protectedProperty; // Error - not accessible outside
    // echo $obj->privateProperty; // Error - not accessible outside
    $obj->showProperties(); // Methods inside the class have access to all properties
    

It is important to understand the difference between scope and namespace. Scope defines the accessibility of variables/functions/constants/classes in a certain execution context. Namespace prevents name conflicts.

What are the scope areas in PHP? — PHP - sobes.tech