Class constants vs static
Learn the difference between class constants and static properties.
Class constants vs static properties
Class constants (const) and static properties both hold class-level data, but they differ in key ways.
A class constant is immutable: once defined, it cannot be reassigned. A static property can be changed at runtime: Counter::$count = 5; is valid.
Constants are initialized with a constant expression for simple types (number, string, array, bool, null). Static properties can be initialized with any expression but computation happens in the constructor.
When to use const, when to use static
Which should you pick? A constant when the value never changes: pi, an HTTP status code, a configuration key. A static property when the value can change at runtime: a counter, a cache, a session count.
Example: class Config { const int MAX_USERS = 100; public static int $currentUsers = 0; }. MAX_USERS is a constant (immutable), $currentUsers is a static property (incremented/decremented).
Practical rule of thumb: if the value stays the same for the whole program, use const; if it changes, use static.
Exercise Counter class: const vs static
Define a Counter class with const int MAX = 3; and public static int $count = 0;. Add public static function increment(): void that does self::$count++. Then call Counter::increment() three times and print echo Counter::$count . "/" . Counter::MAX . "\n";. (Expected output: 3/3)
Show example solution
void { self::$count++; } } then call Counter::increment(); three times, then echo Counter::$count . "/" . Counter::MAX . "\n";
Example solution:
<?php
// Define a Counter class
class Counter {
const int MAX = 3;
public static int $count = 0;
public static function increment(): void {
self::$count++;
}
}
Counter::increment();
Counter::increment();
Counter::increment();
echo Counter::$count . "/" . Counter::MAX . "
";
Test yourself
-
Which is a property of a class constant (const)?
- It is immutable
- It can be changed at runtime
- It holds a different value per instance
- It is written with a $ sign
Show answer
It is immutable — Correct. A const-defined constant is immutable.
-
Constant or static?
class Config { ____ }Show answer
class Config { const int MAX_USERS = 100; } -
For 'number of logged-in users' in a web app, what do you use?
- A class constant with const
- A private property
- ::class
- A static property
Show answer
A static property — Correct. The number of logged-in users changes at runtime, so a static property fits.