Back to results for “Scope”
PHP › Traits

How do trait properties and static properties behave when a trait is used by multiple different classes, and is that state actually shared between them?

Intermediate

Answer

A trait can define its own properties, including static properties, and when a trait is used by a particular class, that trait's properties effectively become properties of that specific class, meaning each individual class using the trait gets its own separate, completely independent copy of any regular instance properties, while a static property defined within a trait is shared only among instances of that same specific class, not shared globally across every different class that happens to use the same trait, which is an important distinction to understand correctly.
trait Counter {
    protected static int $count = 0;

    public function increment(): void {
        static::$count++;
    }
}
Real-world example Two completely separate classes both use the same Counter trait, and each class maintains its own entirely independent static counter value, since the static property is scoped to each individual class using the trait rather than being shared globally between them.

Common follow-ups: What would happen if two classes using the same trait were expected to share a single global counter instead?;How does this behavior compare to how static properties normally work within regular class inheritance?