Skip to content
PHP Logo

How does the concept of scope in PHP affect the usage of static variables?

When using static variables in PHP, the concept of scope is important to consider. Static variables retain their value between function calls, but their scope is limited to the function in which they are defined. To access a static variable outside of its defining function, you can use a static method within a class to maintain the variable's value across different function calls.

php
class Example {
    public static function incrementCounter() {
        static $counter = 0;
        $counter++;
        return $counter;
    }
}

// Accessing the static variable outside of its defining function
echo Example::incrementCounter(); // Output: 1
echo Example::incrementCounter(); // Output: 2