PHP Static Methods
Static properties and methods belong to the class itself rather than to any individual object, so you can use them without creating an instance.
What does static mean?
Normally a property or method belongs to a specific object, and you reach it through a variable holding that object. A static member is different: it belongs to the class as a whole. There is only one copy of a static property shared across every use of the class, and you can call a static method without ever creating an object. You declare these members with the static keyword.
A static method and property
<?php
class Counter
{
public static int $count = 0;
public static function increment(): void
{
self::$count++;
}
}
Counter::increment();
Counter::increment();
echo Counter::$count; // 2
?>Notice the double-colon operator (::), also called the scope resolution operator. You use it to reach static members from outside the class, as in Counter::increment(). Inside the class you refer to the class's own static members with the self keyword, as in self::$count.
self versus $this
Because static members are not tied to an object, you cannot use $this inside a static method; there is no particular object for it to point to. Instead you use self:: to reach other static members of the same class. Trying to access a non-static property from a static method will cause an error.
A common use: factory methods
A frequent use of static methods is a factory, a method that builds and returns an object in a convenient way. This lets you offer clear, named ways of constructing objects while keeping the constructor itself simple.
A static factory method
<?php
class Money
{
private function __construct(public int $cents)
{
}
public static function fromDollars(float $dollars): self
{
return new self((int) round($dollars * 100));
}
public function format(): string
{
return "$" . number_format($this->cents / 100, 2);
}
}
$price = Money::fromDollars(19.5);
echo $price->format(); // $19.50
?>- Declare static members with the static keyword.
- Access them through the class name and the :: operator from outside.
- Use self:: to reach static members from within the same class.
- You cannot use $this inside a static method.
- Static properties keep a single shared value across the whole program run.
Exercise: PHP OOP
What is the difference between a private and a protected property?