PHP Static Methods
A static method belongs to the class itself, not to any instance. Call it with Class::method() — no new needed.
Defining one
PHP
class MathUtils {
public static function square(int $n): int {
return $n * $n;
}
public static function clamp(int $n, int $min, int $max): int {
return max($min, min($max, $n));
}
}
echo MathUtils::square(5); // 25
echo MathUtils::clamp(120, 0, 100); // 100
self vs static
| Keyword | Refers to |
|---|---|
self:: | The class where the method is declared. |
static:: | The runtime class (late static binding). |
PHP
class Animal {
public static function fresh(): static {
return new static(); // returns runtime class
}
}
class Dog extends Animal {}
$d = Dog::fresh(); // a Dog, not just an Animal
Common uses
- Factories —
User::find(42),Money::fromDollars(9.99). - Helpers — pure functions grouped under a class name.
- Singletons (use sparingly — global state is hard to test).
Watch out
- No
$thisinside a static method — it doesn't belong to an instance. - Static methods are global-ish state. They're hard to mock in tests. Prefer constructor injection for collaborators.
- If your "helper" class is mostly static methods that operate on data, it might want to be a regular class with state.
Tip: Factory pattern + late static binding:
public static function create(): static { return new static(); } works correctly in every subclass without overriding.Example
Example
<?php
class Math {
public static function square(int $n): int {
return $n * $n;
}
}
echo Math::square(5);
Try it Yourself »
Exercise
Static reference to the same class.
::square(5);
The class name from the example.
Discussion
Loading…