PHP
static property
Learn to hold shared state on the class with static properties.
static property
A static property belongs to the class itself, not to an instance. It is declared with the static keyword: public static int $count = 0. The key trait: all instances of the same class share this property. When one instance changes the value, every other instance sees the new value.
Access is different too: instead of $obj->prop, you write Counter::$count using the class name. The :: token is the scope resolution operator. So a static property fits shared state like instance counts or counters.
Declaring and using a static property
Let's define a Counter class. With public static int $total = 0, the value belongs to the class. From outside you read or write it as Counter::$total; no need to call new first.
Inside a constructor, writing Counter::$total++ makes the shared counter grow on every new Counter(). You can track the total number of instances this way.
Note: accessing a static property via $obj->total is discouraged in PHP 8.3; always use Counter::$total.
Exercise Counter class: instance counter with a static property
Define a Counter class with a public static int $total = 0 property. The constructor (__construct) increments the counter with Counter::$total++ on every call. Call new Counter() three times and finally print the counter with echo Counter::$total . "\n".
Show example solution
:$total++ in the constructor, call new Counter() three times, then echo Counter::$total . "\n".
Example solution:
<?php
// Define a Counter class
class Counter {
public static int $total = 0;
public function __construct() {
Counter::$total++;
}
}
new Counter();
new Counter();
new Counter();
echo Counter::$total . "\n";
Test yourself
-
When is a static property useful?
- When each instance should hold its own value
- When the value is shared across all instances
- When the value is only used in the constructor
- When the property is a string
Show answer
When the value is shared across all instances — Correct. A static property is for state shared across all instances.
-
Declare a static property
class Counter {
public ____
}
echo Counter::$count;
Show answer
class Counter {
public static int $count = 0;
}
echo Counter::$count;
-
Match the static property expressions
- public static $count
- Class-level property
- Counter::$count
- External access
- static keyword
- Shared state marker
- $obj->count
- Discouraged access
Next lesson: static method