Understanding the static Keyword in PHP with Use Cases

Master the use of the static keyword in PHP with clear examples. Learn how it works in functions, classes, and inheritance, including the key difference between self:: and static::.

Understanding the static Keyword in PHP with Use Cases Image

The static keyword in PHP is used in three main ways:

1. Static Variables in Functions

Static variables retain their values between function calls.

function counter() {
    static $count = 0;
    $count++;
    echo $count;
}

Each call to counter() will increment the same $count.

2. Static Properties and Methods

Used when you want to access class members without creating an object.

class Math {
    public static $pi = 3.14;

    public static function getPi() {
        return self::$pi;
    }
}

echo Math::getPi(); // 3.14

3. Late Static Binding

static:: respects the runtime (called) class, unlike self::, which uses the defining class.

class ParentClass {
    protected static function who() {
        echo "Parent\n";
    }
    public static function test() {
        static::who(); // Late static binding
    }
}
class ChildClass extends ParentClass {
    protected static function who() {
        echo "Child\n";
    }
}
ChildClass::test(); // Outputs: Child

self:: vs static::

  • self:: = early binding (class where method is defined).
  • static:: = late binding (class that was called).

Use static:: when working with inheritance and overridden methods.

Conclusion:

The static keyword is versatile in PHP, helping manage memory in functions, class-level utilities, and polymorphic behavior in OOP.

Happy Coding! 😊

Tags

PHP

Do you Like?