Static Properties and Methods
Static members belong to the class itself, not to any object.
Syntax
ClassName::$property;
ClassName::method();A static property or method belongs to the class rather than to any single object. You access static members with the :: operator, using the class name.
Inside the class, refer to static members with self::.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Maintain a shared request counter across all instances of a Router class using a static property.
- Implement a factory method as a static method that validates arguments and returns a new instance.
- Store application-wide configuration in static properties on a Config class to avoid repeated DB lookups.
More examples
Static property counter
A static property is shared across all instances; the counter increments with every new object created.
<?php
class Request {
private static int $count = 0;
public function __construct() {
self::$count++;
}
public static function getCount(): int {
return self::$count;
}
}
new Request();
new Request();
new Request();
echo Request::getCount(); // 3Static factory method
A static factory method provides a named, meaningful way to construct an object from a different input format.
<?php
class Color {
private function __construct(
public readonly int $r,
public readonly int $g,
public readonly int $b
) {}
public static function fromHex(string $hex): self {
$hex = ltrim($hex, '#');
return new self(
hexdec(substr($hex, 0, 2)),
hexdec(substr($hex, 2, 2)),
hexdec(substr($hex, 4, 2))
);
}
}
$red = Color::fromHex('#ff0000');
echo $red->r; // 255Calling static methods
Static methods are called on the class name with ::, not on an instance, making them ideal for stateless utility functions.
<?php
class MathHelper {
public static function clamp(float $v, float $min, float $max): float {
return max($min, min($max, $v));
}
public static function lerp(float $a, float $b, float $t): float {
return $a + ($b - $a) * $t;
}
}
echo MathHelper::clamp(150, 0, 100); // 100
echo MathHelper::lerp(0, 10, 0.25); // 2.5
Discussion