PHP
static method
Learn to write methods callable without an instance with static methods.
static method
A static method belongs to the class, not to an instance. It is declared as public static function square(int $n): int. To call it, you do not need new: MathHelper::square(4) runs directly and returns 16.
Important: a static method cannot use $this. The $this pseudo-variable points to an instance, and there is no instance in a static method. You can only reach static properties and other static methods.
Static methods are ideal for stateless work like math helpers, converters or factory methods that do not need instance state.
Declaring and calling a static method
Let's define a MathHelper class. With public static function square(int $n): int { return $n * $n; } inside, you call it from outside as MathHelper::square(5); the result is 25.
Several static methods can sit side by side in the same class: square, cube, double. Each is called as MathHelper::methodName(arg). No need to instantiate (new MathHelper()).
This is handy for grouping helper functions; the class acts like a namespace.
Exercise MathHelper: square and cube static methods
Define a MathHelper class with two static methods: square(int $n): int returns the square, cube(int $n): int returns the cube. Then print the results with echo MathHelper::square(4) . "\n" and echo MathHelper::cube(3) . "\n".
Show example solution
int { return $n * $n; }, return $n * $n * $n for cube, then echo MathHelper::square(4) . "\n"; and echo MathHelper::cube(3) . "\n";.
Example solution:
<?php
// Define a MathHelper class
class MathHelper {
public static function square(int $n): int {
return $n * $n;
}
public static function cube(int $n): int {
return $n * $n * $n;
}
}
echo MathHelper::square(4) . "\n";
echo MathHelper::cube(3) . "\n";
Test yourself
-
Which of these can a static method NOT use?
- Other static methods
- Static properties
- $this pseudo-variable
- Returning a value
Show answer
$this pseudo-variable — Correct. $this cannot be used in a static method; there is no instance context.
-
Static method call
class MathHelper {
public static function square(int $n): int {
return $n * $n;
}
}
echo ____
Show answer
class MathHelper {
public static function square(int $n): int {
return $n * $n;
}
}
echo MathHelper::square(5);
-
Match the static method expressions
- public static function
- Method declaration
- MathHelper::square(4)
- Call example
- $this
- Cannot be used in static
- return $n * $n
- Return value
Next lesson: In-class access with self::