Static members
suggest changeA static member belongs to the class itself, not to any particular object. A static property has one value for the whole class (and, unless redeclared, its subclasses). A static method runs without an object, so it has no $this.
This article covers:
- declaring and accessing static properties and methods
- typed static properties, initialization and errors
- how static properties behave with inheritance
- named constructors, per-class registries and other common uses
- static variables in functions and methods, and static closures
- static methods as callables, in interfaces and abstract classes
- PHP 8.5 asymmetric visibility for static properties
- why static state makes code hard to test, and what to do instead
Related topics: Late static binding, this self and static plus the singleton, Static properties and variables, Class Constants and Properties.
Static properties and methods
Add the static keyword to a property or method. Access them with the scope resolution operator ::, either through the class name or, inside the class, through self:: or static:::
<?php
class Counter
{
public static int $count = 0;
private static array $log = [];
public static function increment(): int
{
self::$log[] = 'increment';
return ++self::$count;
}
public static function log(): array
{
return self::$log;
}
}
Counter::increment();
Counter::increment();
Counter::$count += 10; // public: writable from outside
echo Counter::$count, "\n";
echo Counter::increment(), "\n";
print_r(Counter::log());
Output:
12
13
Array
(
[0] => increment
[1] => increment
[2] => increment
)
Note the $ in Counter::$count. It's what tells a static property apart from a class constant (Counter::MAX). No object was ever created: the values live in the class and last until the script (or request) ends.
Visibility (public, protected, private) works the same as for instance members. See Method and Property Visibility.
Static methods have no $this
A static method isn't called on an object, so $this doesn't exist inside it. You also can't call an instance method statically:
<?php
class Temperature
{
public static function celsiusToFahrenheit(float $c): float
{
return $c * 9 / 5 + 32;
}
public function broken(): void {}
public static function usesThis(): string
{
return get_class($this);
}
}
echo Temperature::celsiusToFahrenheit(100), "\n";
try {
Temperature::usesThis();
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
try {
Temperature::broken();
} catch (Error $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
Output:
212
Error: Using $this when not in object context
Error: Non-static method Temperature::broken() cannot be called statically
Going the other way is fine: an instance method can call static methods and read static properties with self:: or static::.
Accessing static members through an instance
A static method can also be called through an object, with either $obj::method() or $obj->method(). A static property, however, must always be accessed with ::. Using -> looks for an instance property:
<?php
set_error_handler(function (int $no, string $msg): bool {
echo "PHP warning/notice: $msg\n";
return true;
});
class Config
{
public static string $env = 'dev';
public static function describe(): string
{
return 'env=' . static::$env;
}
}
$cfg = new Config();
// all of these call the same static method
echo Config::describe(), "\n";
echo $cfg::describe(), "\n";
echo $cfg->describe(), "\n";
// a class name stored in a string works too
$class = 'Config';
echo $class::describe(), "\n";
// static property through an instance variable: use ::
echo $cfg::$env, "\n";
// -> looks for an instance property, which doesn't exist
var_dump($cfg->env);
Output:
env=dev
env=dev
env=dev
env=dev
dev
PHP warning/notice: Accessing static property Config::$env as non static
PHP warning/notice: Undefined property: Config::$env
NULL
$obj->staticMethod() works but hides the fact that the method is static. Prefer ClassName::method() so readers know no object state is involved.
Typed static properties and initialization
Static properties can have types (PHP 7.4+). The default value must be a constant expression: literals, arrays, arithmetic, and references to constants are allowed, but function calls and new are not ("Constant expression contains invalid operations" and "New expressions are not supported in this context").
<?php
class Settings
{
public static int $retries = 3;
public static ?string $token = null;
public static array $hosts = ['a.example', 'b.example'];
public static int $timeout = 10 * 60; // constant expression
public static string $label = self::PREFIX . '-v1';
public static int $uninitialized; // typed, no default
const PREFIX = 'app';
}
var_dump(Settings::$timeout, Settings::$label);
try {
echo Settings::$uninitialized;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
try {
Settings::$retries = 'many';
} catch (TypeError $e) {
echo $e->getMessage(), "\n";
}
Settings::$retries = '5'; // coerced: not strict_types
var_dump(Settings::$retries);
try {
echo Settings::$missing;
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
int(600)
string(6) "app-v1"
Typed static property Settings::$uninitialized must not be accessed before initialization
Cannot assign string to property Settings::$retries of type int
int(5)
Access to undeclared static property Settings::$missing
A few points:
- A typed static property without a default is uninitialized, not
null. Reading it throws anError. - Static properties can't be created dynamically. Assigning to an undeclared one is an
Error, unlike instance properties. - With
declare(strict_types=1)the'5'assignment would be aTypeErrortoo.
If you need a value that requires a function call (an object, a value from the environment), initialize it lazily inside a static method, as Clock::now() does further below.
Some features are not available for static properties: they can't be readonly, and they can't have property hooks.
<?php
class X
{
public static readonly int $v;
}
Fatal error: Static property X::$v cannot be readonly
<?php
class Y
{
public static int $v { get => 1; }
}
Fatal error: Cannot declare hooks for static property
For a fixed value, use a class constant instead of a static property.
Asymmetric visibility (PHP 8.5)
PHP 8.4 added asymmetric visibility for instance properties. PHP 8.5 extends it to static properties: you can make a static property publicly readable but writable only inside the class:
<?php
class Registry
{
// PHP 8.5+: anyone can read, only this class can write
public private(set) static array $items = [];
public static function add(string $name): void
{
self::$items[] = $name;
}
}
Registry::add('cache');
Registry::add('mailer');
print_r(Registry::$items);
try {
Registry::$items = [];
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
Array
(
[0] => cache
[1] => mailer
)
Cannot modify private(set) property Registry::$items from global scope
Before 8.5, the same effect needs a private static property and a public static getter.
Static properties and inheritance
A subclass doesn't get its own copy of an inherited static property. Parent and child share the same storage until the child redeclares the property:
<?php
class Base
{
public static int $shared = 0;
public static int $own = 0;
}
class Child extends Base
{
// redeclared: Child now has its own separate copy
public static int $own = 0;
}
Child::$shared = 5; // writes Base::$shared
Child::$own = 7; // writes Child::$own only
echo 'Base::$shared = ', Base::$shared, "\n";
echo 'Child::$shared = ', Child::$shared, "\n";
echo 'Base::$own = ', Base::$own, "\n";
echo 'Child::$own = ', Child::$own, "\n";
Output:
Base::$shared = 5
Child::$shared = 5
Base::$own = 0
Child::$own = 7
When a subclass redeclares a property, which copy a method sees depends on whether it uses self:: or static:::
<?php
class Car
{
protected static string $brand = 'unknown';
public static function selfBrand(): string { return self::$brand; }
public static function staticBrand(): string { return static::$brand; }
}
class Bmw extends Car
{
protected static string $brand = 'BMW';
}
echo Bmw::selfBrand(), "\n";
echo Bmw::staticBrand(), "\n";
Output:
unknown
BMW
self:: always means the class where the method is written (Car). static:: means the class the method was called on (Bmw). This is late static binding.
Per-subclass state without redeclaring
Redeclaring a property in every subclass is easy to forget. A more robust way to keep separate state per subclass is a single array keyed by static::class:
<?php
abstract class Model
{
private static array $counts = [];
public function __construct()
{
// key by the actual class so each subclass gets its own count
self::$counts[static::class] = (self::$counts[static::class] ?? 0) + 1;
}
public static function created(): int
{
return self::$counts[static::class] ?? 0;
}
}
class User extends Model {}
class Post extends Model {}
new User(); new User(); new User();
new Post();
echo 'users: ', User::created(), "\n";
echo 'posts: ', Post::created(), "\n";
Output:
users: 3
posts: 1
Named constructors (static factory methods)
A very common use of static methods is creating objects. A static factory can have a descriptive name, validate or convert its input, and return static so subclasses get instances of their own type:
<?php
class Money
{
private function __construct(
public readonly int $cents,
public readonly string $currency,
) {}
public static function fromDecimal(string $amount, string $currency): static
{
return new static((int) round((float) $amount * 100), $currency);
}
public static function zero(string $currency): static
{
return new static(0, $currency);
}
public function __toString(): string
{
return sprintf('%d.%02d %s', intdiv($this->cents, 100), $this->cents % 100, $this->currency);
}
}
class Price extends Money {}
echo Money::fromDecimal('19.99', 'USD'), "\n";
echo Money::zero('EUR'), "\n";
echo get_class(Price::zero('PLN')), "\n";
try {
new Money(100, 'USD');
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
19.99 USD
0.00 EUR
Price
Call to private Money::__construct() from global scope
The private constructor forces callers to go through the factories. new static(...) creates an instance of the class the factory was called on, so Price::zero() returns a Price. With new self(...) it would always be a Money. PHP's own DateTimeImmutable::createFromFormat() is a static factory of this kind.
Static variables in functions and methods
A local variable declared with static keeps its value between calls to the same function. It's initialized only the first time the function runs:
<?php
function nextId(): int
{
static $id = 0; // initialized once, kept between calls
return ++$id;
}
echo nextId(), ' ', nextId(), ' ', nextId(), "\n";
function fib(int $n): int
{
static $memo = [0 => 0, 1 => 1];
return $memo[$n] ??= fib($n - 1) + fib($n - 2);
}
echo fib(90), "\n";
// PHP 8.3+: the initializer can be any expression, evaluated on first call
function startedAt(): string
{
static $t = hrtime(true);
return 'first call at ' . $t;
}
var_dump(startedAt() === startedAt());
Output:
1 2 3
2880067194370816120
bool(true)
fib() uses a static array as a memoization cache, which turns exponential recursion into linear. Before PHP 8.3, a static variable's initializer had to be a constant expression; static $t = hrtime(true); was a compile error.
Static variables in methods follow the method. Since PHP 8.1, an inherited method shares its static variables between the parent and child classes. A method that is overridden is a different method with its own variables:
<?php
class A
{
public static function counter(): int
{
static $n = 0;
return ++$n;
}
}
class B extends A {}
// PHP 8.1+: one static variable shared by A::counter() and B::counter()
echo A::counter(), A::counter(), B::counter(), B::counter(), "\n";
class C extends A
{
// overriding creates a new method with its own static variable
public static function counter(): int
{
static $n = 100;
return ++$n;
}
}
echo C::counter(), ' ', A::counter(), "\n";
Output:
1234
101 5
Before PHP 8.1, B::counter() would have had its own copy, printing 1212. Static variables also work in instance methods; the value is shared by all instances, not stored per object. Static properties and variables shows a singleton built on this.
Static closures
A closure created inside an instance method automatically binds $this. Marking it static prevents that. The closure is a little lighter, and it doesn't keep the object alive for as long as the closure exists:
<?php
class Report
{
private array $rows = [1, 2, 3];
public function totals(): array
{
// a normal closure created in a method captures $this automatically
$withThis = function () { return count($this->rows); };
// a static closure doesn't bind $this
$pure = static fn(int $x): int => $x * 2;
return [$withThis(), array_map($pure, $this->rows)];
}
public function broken(): mixed
{
$f = static function () { return $this->rows; };
return $f();
}
}
$r = new Report();
print_r($r->totals());
try {
$r->broken();
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
Array
(
[0] => 3
[1] => Array
(
[0] => 2
[1] => 4
[2] => 6
)
)
Using $this when not in object context
Using static fn for callbacks that don't need the object is a good habit, especially for closures that get stored (event listeners, caches), where an accidental $this capture leaks memory.
Static methods as callables
There are several ways to pass a static method where a callable is expected:
<?php
class Str
{
public static function shout(string $s): string
{
return strtoupper($s) . '!';
}
}
$words = ['hi', 'bye'];
echo implode(' ', array_map([Str::class, 'shout'], $words)), "\n"; // array callable
echo implode(' ', array_map('Str::shout', $words)), "\n"; // string callable
echo implode(' ', array_map(Str::shout(...), $words)), "\n"; // first-class callable
$method = 'shout';
echo Str::$method('dynamic'), "\n"; // variable method name
echo call_user_func([Str::class, 'shout'], 'call'), "\n";
Output:
HI! BYE!
HI! BYE!
HI! BYE!
DYNAMIC!
CALL!
The first-class callable syntax Str::shout(...) (PHP 8.1+) is the best choice: it creates a Closure, a typo in the method name fails immediately at that line, and IDEs and static analyzers can follow it. Be careful with Str::$method(): it's a call through a variable method name, while Str::$method without parentheses reads a static property named $method.
Static methods in interfaces and abstract classes
Interfaces can declare static methods, and abstract classes can declare abstract static methods. Combined with a class name stored in a variable, this gives polymorphism without objects:
<?php
interface Parser
{
public static function extensions(): array;
public static function parse(string $text): array;
}
final class CsvParser implements Parser
{
public static function extensions(): array { return ['csv']; }
public static function parse(string $text): array
{
$lines = explode("\n", trim($text));
return array_map(fn(string $line) => explode(',', $line), $lines);
}
}
final class JsonParser implements Parser
{
public static function extensions(): array { return ['json']; }
public static function parse(string $text): array
{
return json_decode($text, true, flags: JSON_THROW_ON_ERROR);
}
}
/** @param class-string<Parser> $parser */
function load(string $parser, string $text): array
{
return $parser::parse($text);
}
echo json_encode(load(CsvParser::class, "a,b\n1,2")), "\n";
echo json_encode(load(JsonParser::class, '{"x": [1, 2]}')), "\n";
echo implode(', ', JsonParser::extensions()), "\n";
Output:
[["a","b"],["1","2"]]
{"x":[1,2]}
json
PHP's type system can't express "a class name implementing Parser", so the class-string<Parser> docblock is there for static analyzers like PHPStan and Psalm.
An abstract class can call its abstract static method through static::. Calling it directly on the abstract class fails:
<?php
abstract class Shape
{
abstract public static function sides(): int;
public static function describe(): string
{
return static::class . ' has ' . static::sides() . ' sides';
}
}
class Triangle extends Shape
{
public static function sides(): int { return 3; }
}
echo Triangle::describe(), "\n";
try {
Shape::describe();
} catch (Error $e) {
echo $e->getMessage(), "\n";
}
Output:
Triangle has 3 sides
Cannot call abstract method Shape::sides()
Inspecting static members
isset() works on static properties, and reflection can list and change them, including non-public ones:
<?php
class Feature
{
public static bool $darkMode = true;
protected static int $limit = 50;
public static ?string $beta = null;
public static function run(): void {}
public function render(): void {}
}
var_dump(isset(Feature::$darkMode), isset(Feature::$beta));
$ref = new ReflectionClass(Feature::class);
print_r($ref->getStaticProperties());
$ref->setStaticPropertyValue('limit', 100);
echo $ref->getStaticPropertyValue('limit'), "\n";
foreach ($ref->getMethods() as $m) {
echo $m->getName(), ': ', $m->isStatic() ? 'static' : 'instance', "\n";
}
Output:
bool(true)
bool(false)
Array
(
[darkMode] => 1
[limit] => 50
[beta] =>
)
100
run: static
render: instance
When to use static, and when not to
Good uses of static members:
- pure helper functions that need no state, such as
Temperature::celsiusToFahrenheit(). A namespaced plain function is often just as good. - named constructors like
Money::fromDecimal() - per-request caches and registries, where sharing state is the whole point
- metadata about a class, such as
Parser::extensions()
Static properties are global variables with a class name in front. Any code can change them, the changes are invisible at the call site, and the values persist across tests in the same PHPUnit process. Code that depends on static state needs manual resets:
<?php
class Clock
{
private static ?DateTimeImmutable $frozen = null;
public static function now(): DateTimeImmutable
{
return self::$frozen ?? new DateTimeImmutable();
}
// test helpers: every test must remember to undo this
public static function freeze(string $at): void
{
self::$frozen = new DateTimeImmutable($at);
}
public static function reset(): void
{
self::$frozen = null;
}
}
Clock::freeze('2026-01-01 12:00:00');
echo Clock::now()->format('Y-m-d H:i'), "\n";
Clock::reset();
echo Clock::now() > new DateTimeImmutable('2026-01-02') ? "real time\n" : "still frozen\n";
// the alternative: pass a clock object in
interface ClockInterface { public function now(): DateTimeImmutable; }
final class FixedClock implements ClockInterface
{
public function __construct(private DateTimeImmutable $at) {}
public function now(): DateTimeImmutable { return $this->at; }
}
final class InvoiceService
{
public function __construct(private ClockInterface $clock) {}
public function dueDate(): string
{
return $this->clock->now()->modify('+30 days')->format('Y-m-d');
}
}
$svc = new InvoiceService(new FixedClock(new DateTimeImmutable('2026-03-01')));
echo $svc->dueDate(), "\n";
Output:
2026-01-01 12:00
real time
2026-03-31
The second version gets its dependency through the constructor, so a test simply passes a different object and nothing needs resetting. Static methods also can't be replaced by mocks, which is another reason to keep them for code without side effects. (In real code, use the standard Psr\Clock\ClockInterface from PSR-20 rather than defining your own.)
Also remember that static state lasts only as long as the PHP process keeps the class loaded. Under PHP-FPM that's one request; in long-running servers such as RoadRunner, Swoole or FrankenPHP worker mode, static properties survive across requests, so a static cache can leak data from one user's request into the next.
Summary
staticmembers belong to the class: access them withClassName::$propandClassName::method(), orself::/static::inside the class.- Static methods have no
$this. Static properties must be accessed with::, never->. - Typed static properties without a default are uninitialized; static properties can't be
readonly, can't have hooks, and can't be created dynamically. - PHP 8.5 allows asymmetric visibility such as
public private(set) static. - Subclasses share the parent's static property unless they redeclare it; use
static::to reach the redeclared copy, or key an array bystatic::class. - Static factories returning
staticare a clean way to build objects. - Static variables in functions persist between calls; since PHP 8.1 they're shared by inherited methods, and since PHP 8.3 they can have any initializer.
- Use
static fnfor closures that don't need$this, andClass::method(...)to pass a static method as a callable. - Treat static properties as global state: prefer injected objects for anything that tests need to replace.