Static properties belong to the class itself rather than an instance. They’re declared with the static
keyword and shared across all objects. Access them using ClassName::$property
or self::$property
inside the class. They’re ideal for shared values like counters, settings, or global state. Unlike normal properties, static ones persist independently of instances.
1. Basic Static Property Example
class Counter {
public static $count = 0;
public function increment() {
self::$count++;
}
public function getCount() {
return self::$count;
}
}
$obj1 = new Counter();
$obj1->increment();
$obj2 = new Counter();
$obj2->increment();
echo $obj2->getCount(); // Output: 2 (shared between all objects)
File: static_property_basic.php
2. Accessing Static Property Without Object
class Settings {
public static $appName = "MyApp";
}
echo Settings::$appName; // Output: MyApp
File: static_direct_access.php
3. Static Property in Inheritance
class ParentClass {
protected static $message = "Hello from parent";
public static function getMessage() {
return static::$message;
}
}
class ChildClass extends ParentClass {}
echo ChildClass::getMessage(); // Output: Hello from parent
File: static_inheritance_property.php
4. Key Rules of Static Properties
Rule | Description |
---|---|
Declared with static keyword |
public static $name = "value"; |
Accessed via ClassName::$x |
No need to create object |
Shared among all instances | Value is common across all objects |
Used for shared state/config | Like counters, settings, config values |