Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 147 ยท Object-Oriented PHP

Static Properties and Methods

Learn PHP static properties and methods, self:: vs static:: and late static binding, named constructors, static factories and the risks of static state.

Everything in the previous lessons belonged to an object: each BankAccount had its own balance, and $this pointed at one particular instance. Some things, though, belong to the class as a whole. A function that converts Fahrenheit to Celsius doesn't need any object's data. A counter of how many orders were created this request isn't a property of any single order. A method that creates objects can't be called on an object that doesn't exist yet.

For these, PHP has static members, declared with the static keyword and accessed with the :: operator (officially called the scope resolution operator) on the class name, not with -> on an object. This lesson covers static properties and methods, self:: and the difference between self:: and static:: (late static binding), named constructors and static factories, and the reasons experienced developers keep static state to a minimum.

Static methods

A static method is declared with static and called on the class: ClassName::method(). It has no $this, because no object is involved:

PHP Static utility methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

self:: inside a class means "this class", so self::celsiusToFahrenheit() calls a sibling static method. It's preferred over writing Temperature:: because it keeps working if the class is renamed.

Static methods follow the same visibility rules as other methods (public, protected, private) and the same type declarations. Two mistakes produce errors you should recognize:

PHP Static and non-static do not mix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The two errors are "Using $this when not in object context" and "Non-static method Report::title() cannot be called statically". The opposite direction is allowed: you can call a static method through an object ($report::make() or even $report->make()), though writing the class name is clearer.

Should a helper be a static method or a function?

Pure helpers like celsiusToFahrenheit() don't need a class at all; a plain function (inside a namespace) works just as well. Static methods are a good choice when the helper clearly belongs to a class's concept, needs access to its private constants or members, or creates instances of it, which leads to the most valuable use of static methods: named constructors.

Static properties

A static property belongs to the class, so there's exactly one copy shared by all instances (and by code that has no instance at all). Access it with self::$name inside the class and ClassName::$name outside. Note the $: it stays on static property names, unlike $this->name.

PHP One shared value for the whole class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

All three tickets increment the same $nextNumber, which is how they get consecutive numbers. Changing the public static $prefix from outside affects every later ticket, which is convenient here, and also a first hint of the risk discussed at the end of this lesson.

Static properties can have types and defaults like normal properties. They live for the whole request (or CLI run); each new web request starts with fresh defaults, because PHP shares nothing between requests.

Static properties and inheritance

A child class shares its parent's static property unless it redeclares it:

PHP Shared or redeclared in a child

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$loaded isn't redeclared, so Model, User and Post all share one counter, which reaches 3. $table is redeclared, so each class has its own value. The method table() uses static::, not self::, to read it. That difference is the topic of the next section. (Traits behave differently: each class using a trait gets its own copy of its static properties, as shown in Traits.)

self:: vs static:: (late static binding)

self:: is resolved where the code is written: in Model, self:: always means Model. static:: is resolved where the code is called: if you call User::table(), then static:: inside the inherited method means User. Because the decision is made at runtime, this is called late static binding.

The difference matters most when a parent creates objects:

PHP new self() vs new static()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Circle::createSelf() returns a Shape, because new self() written inside Shape always means Shape. Circle::createStatic() returns a Circle. Method calls work the same way: self::name() is always Shape::name(), while static::name() picks up the override when the call is Circle::kind(). self, static and parent only make sense inside a class; using static:: outside one is an error ("Cannot use "static" when no class scope is active").

Rules of thumb:

  • Use static:: (and new static(), return type static) in code that child classes inherit and that should adapt to them: factories in base classes, fluent methods, overridable static settings like $table.
  • Use self:: when you mean exactly this class, for example private constants or private static helpers that children can't override anyway.
  • The static return type (PHP 8.0) tells callers that the method returns an instance of the called class. It's the right type for methods that return $this in fluent interfaces as well.

Three meanings of static. The keyword is reused: static members belong to the class; static:: is late static binding; and a static $count = 0; variable inside a function keeps its value between calls (from Variable Scope). They're unrelated features that share a word.

Named constructors and static factories

PHP allows only one __construct() per class, so how do you create a Duration from seconds in one place and from a string like "1h 30m" in another? Overloading isn't available. The standard answer is named constructors: public static methods with descriptive names that each build an instance. Make the real constructor private and they become the only way in:

PHP Named constructors with a private constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The names say what each argument means, so Duration::ofMinutes(95) can't be misread the way new Duration(95) could. All validation still runs in one place, the private constructor. The class is final, so new self() is the right choice; in a class designed for extension you'd write new static(). Calling new Duration(10) from outside throws "Call to private Duration::__construct() from global scope".

You've already used this pattern in PHP itself: DateTimeImmutable::createFromFormat() is a named constructor (see Dates and Times), and backed enums have from() and tryFrom().

A static factory is the same idea taken one step further: a static method that decides which class to instantiate. For example, Notifier::for('sms') might return an SmsNotifier or an EmailNotifier, both implementing a Notifier interface. Factories are covered with other patterns in Design Patterns in PHP.

Why static state is risky

Static methods that compute results from their arguments are harmless. Static properties that change at runtime are different: they're global variables with a class name in front, and they bring every problem from Variable Scope:

  • Hidden coupling. Any code anywhere can change Ticket::$prefix, and nothing in a method's signature reveals that it reads it. Bugs appear far from their cause.
  • Leaking between tests. A test that increments a static counter leaves it changed for the next test in the same process. Test results start depending on execution order.
  • Hard to replace. Code that calls Database::query() directly is welded to that class. Code that receives a database object through its constructor can be handed a test double instead.
  • Long-running processes. In a normal web request, static state resets for each request. In queue workers, Swoole, RoadRunner or FrankenPHP worker mode, one PHP process serves many requests, so static data from one user's request can leak into the next.
PHP Static state leaking between uses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both customers see book, lamp, because the "cart" is really one global list. Making $items a normal (non-static) property fixes it. The singleton pattern, a class that keeps its only instance in a static property, has the same drawbacks, which is why modern frameworks use a dependency injection container instead (Design Patterns in PHP shows both).

Good uses of static, then:

  • Named constructors and factories.
  • Pure helpers that belong to a class's concept.
  • Caches of immutable, computed data (like a parsed config) that can never be wrong for another user.
  • Class-level configuration read through static:: that subclasses override, like $table above, as long as nothing changes it at runtime.

For constants that never change at all, prefer class constants, the next lesson's topic, over static properties.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a static method uses $this?

    A static method runs without an object, so $this doesn't exist. Use self:: or static:: for class-level members.
  2. 2. Base has public static function make(): static { return new static(); }. What does get_class(Child::make()) return, if Child extends Base?

    static:: and new static() use late static binding, so they refer to the class the method was called on, Child.
  3. 3. Model declares public static int $count = 0; and User extends Model without redeclaring it. After User::$count++; Model::$count++;, what is User::$count?

    A child shares its parent's static property unless it redeclares it, so both lines increment the same counter.
  4. 4. Why give a class a private constructor and public static methods like ofMinutes() and fromString()?

    These named constructors describe what the arguments mean, while the private constructor keeps all validation in one place.
  5. 5. A Cart class stores items in private static array $items. Two Cart objects each add one item. How many items does each cart report?

    A static property has a single copy for the whole class, so both objects read and write the same list. That's why static state is risky.

Summary

  • static members belong to the class, not to an object. Access them with ClassName::method(), ClassName::$property, and inside the class with self:: or static::.
  • Static methods have no $this; calling an instance method statically throws an Error.
  • A static property has one copy shared by all instances. A child class shares its parent's static property unless it redeclares it (traits give each class its own copy).
  • self:: means the class where the code is written; static:: means the class the call was made on (late static binding). Use new static() and the static return type in inheritable code.
  • Named constructors (Duration::ofMinutes()) plus a private constructor give clear, validated ways to create objects. Static factories choose which class to create.
  • Mutable static state is global state: it couples code, leaks between tests and between requests in long-running workers. Prefer instance properties and dependency injection.

Next: Class Constants and Enums