PHP Static Methods & Properties
Normally properties and methods belong to an object: each new creates a fresh set of values. A static member instead belongs to the class itself. There is exactly one copy, shared by everyone, and you can use it without creating an object at all.
Static methods
Declare a method with the static keyword and call it with the scope resolution operator ::.
<?php
class Temperature
{
public static function toFahrenheit(float $c): float
{
return $c * 9 / 5 + 32;
}
public static function toCelsius(float $f): float
{
return round(($f - 32) * 5 / 9, 1);
}
}
echo Temperature::toFahrenheit(25), "\n";
echo Temperature::toCelsius(100), "\n";77
37.8
Static methods are a natural home for helpers that do not need any object state — conversions, validators, factories.
Note: Inside a static method there is no object, so
$thisis not available. Trying to use it causes an Error.
Static properties
A static property is shared by all instances. Inside the class, refer to it with self::$name (note the $).
<?php
class Visitor
{
public static int $count = 0;
public function __construct(public string $name)
{
self::$count++;
}
}
new Visitor("Ana");
new Visitor("Ben");
$c = new Visitor("Chen");
echo "Visitors so far: ", Visitor::$count, "\n";
echo "Last visitor: ", $c->name, "\n";Visitors so far: 3
Last visitor: Chen
Every constructor call increments the same counter, because $count lives on the class, not on each visitor.
Instance vs static at a glance
| Instance member | Static member | |
|---|---|---|
| Belongs to | Each object | The class |
| Declared as | public $x / public function f() |
public static $x / public static function f() |
| Accessed from outside | $obj->x, $obj->f() |
ClassName::$x, ClassName::f() |
| Accessed inside | $this->x |
self::$x or static::$x |
Needs new? |
Yes | No |
Factory methods
A very common pattern is the static factory: a static method that builds and returns an object, often with a more descriptive name than the constructor.
<?php
class Money
{
private function __construct(private int $cents) {}
public static function fromEuros(float $euros): self
{
return new self((int) round($euros * 100));
}
public static function zero(): self
{
return new self(0);
}
public function add(Money $other): self
{
return new self($this->cents + $other->cents);
}
public function format(): string
{
return number_format($this->cents / 100, 2) . " EUR";
}
}
$total = Money::zero()
->add(Money::fromEuros(12.5))
->add(Money::fromEuros(7.25));
echo $total->format(), "\n";19.75 EUR
Because the constructor is private, the only way to create Money is through the factories.
self:: vs static:: (late static binding)
self:: always means "the class where this code is written". static:: means "the class that was actually called" — it is resolved at runtime. This difference matters with inheritance:
<?php
class Model
{
public static function create(): static
{
return new static();
}
public static function selfName(): string
{
return self::class;
}
public static function staticName(): string
{
return static::class;
}
}
class User extends Model {}
echo get_class(User::create()), "\n";
echo User::selfName(), "\n";
echo User::staticName(), "\n";User
Model
User
Tip: Use
static::(and thestaticreturn type) in base-class factories so that subclasses get instances of themselves.
A simple registry
Static properties can hold shared configuration or caches. Just remember that this is global state: it is shared across the entire request.
<?php
class Config
{
private static array $values = [];
public static function set(string $key, mixed $value): void
{
self::$values[$key] = $value;
}
public static function get(string $key, mixed $default = null): mixed
{
return self::$values[$key] ?? $default;
}
}
Config::set("app.name", "TAD Shop");
Config::set("app.debug", false);
echo Config::get("app.name"), "\n";
var_dump(Config::get("app.debug"));
echo Config::get("app.locale", "en"), "\n";TAD Shop
bool(false)
en
Note: Heavy use of static state makes code harder to test, because every test shares the same values. Prefer passing objects around for anything more than simple helpers and counters.
Test yourself
How do you read a static property $total from inside its own class?
$this->totalself::$totalself->total$this::total
Why can't a static method use $this?
- Because
$thisis read-only - Because static methods are private
- Because there is no object when a static method runs
- It can,
$thisworks everywhere
In a parent class, return new static(); is called as Child::create(). What is created?
- A
Parentobject - A
Childobject - An error
- A
stdClassobject