iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Static Properties

A static property is shared across every instance of the class — and accessible without one.

Declare & use

PHP
class Counter {
    public static int $count = 0;

    public static function bump(): void {
        self::$count++;
    }
}

Counter::bump();
Counter::bump();
Counter::bump();
echo Counter::$count;   // 3

self vs static

Same rules as for static methods — self:: means the declaring class; static:: means the runtime class.

Class constants

For values that never change, prefer constants over static properties:

PHP
class Status {
    public const PAID     = 'paid';
    public const PENDING  = 'pending';
    public const REFUNDED = 'refunded';
}

echo Status::PAID;

When static properties are useful

  • Caches — memoise an expensive computation across instances.
  • Counters — total instances created, total events processed.
  • Configuration — class-wide default settings.
  • Implementing a strict singleton.

When they hurt

  • Hidden global state — tests can't easily reset them.
  • Multi-tenant code — one tenant's data leaks into another's request.
  • Long-lived processes (Swoole, Octane) — static state survives between requests.
Tip: If you reach for a static property, ask: could this be passed as a constructor argument instead? Dependency injection beats hidden state every time.

Example

Example
<?php
class Counter {
    public static int $count = 0;
    public static function bump(): void { self::$count++; }
}
Counter::bump(); Counter::bump(); Counter::bump();
echo Counter::$count;
Try it Yourself »

Exercise

Reference a static property from within the class.

self:: ;

Test yourself

Q1. Static properties are…
Q2. For values that never change prefer…
Q3. Heavy reliance on static state…

Discussion

Loading…