How to Define and Use Static Methods in PHP
In PHP, static methods allow you to call functions within a class
without needing to create an instance of that class first. This article
provides a direct guide on how to define static methods using the
static keyword, how to execute them using the scope
resolution operator (::), and the essential rules to follow
when incorporating them into your object-oriented PHP code.
Defining a Static Method
To define a static method, you place the static keyword
directly after the visibility modifier (such as public,
protected, or private) and before the
function keyword inside your class.
class MathHelper {
public static function add(int $a, int $b): int {
return $a + $b;
}
}Calling a Static Method Externally
To access a static method from outside the class, you do not
instantiate the class using the new keyword. Instead, use
the class name followed by the scope resolution operator
(::) and the method name.
// Calling the static method directly
$result = MathHelper::add(5, 10);
echo $result; // Outputs: 15Calling a Static Method Internally
If you need to call a static method from another method within the
same class, use the self keyword (or static
keyword for late static binding) followed by the double colon
(::).
class MathHelper {
public static function add(int $a, int $b): int {
return $a + $b;
}
public static function average(int $a, int $b): float {
// Calling the static method internally using self
$sum = self::add($a, $b);
return $sum / 2;
}
}
echo MathHelper::average(10, 20); // Outputs: 15Key Rules and Best Practices
- No
$thiscontext: Because static methods are bound to the class itself and not to a specific object instance, the pseudo-variable$thisis not available inside a static method. Attempting to use$thiswill result in a fatal error. - Accessing static properties: Static methods can
access static properties of the same class by using
self::$propertyName. - When to use: Static methods are highly useful for utility or helper classes (e.g., mathematical calculations, string formatting, or database connection helpers) that perform independent operations and do not need to maintain state across multiple instances.