Static methods belong to the class itself and can be called without creating an object. They are declared using the static
keyword. Inside the class, use self::method()
to call them. Static methods are ideal for utility functions and helpers that don’t rely on object properties. They cannot use $this
because there’s no instance context.
1. Basic Static Method Example
class MathHelper {
public static function add($a, $b) {
return $a + $b;
}
}
echo MathHelper::add(5, 3); // Output: 8
File: static_basic.php
2. Accessing Static Methods Inside Class
class Greeting {
public static function sayHello() {
return "Hello!";
}
public function callHello() {
return self::sayHello(); // Use self:: inside class
}
}
$obj = new Greeting();
echo $obj->callHello(); // Output: Hello!
File: static_inside_class.php
3. Static Methods in Inheritance
class ParentClass {
public static function welcome() {
return "Welcome from parent!";
}
}
class ChildClass extends ParentClass {}
echo ChildClass::welcome(); // Output: Welcome from parent!
File: static_inheritance.php
4. Key Features of Static Methods
Feature | Description |
---|---|
Called without object | Use ClassName::method() |
Use self:: inside class |
To access own static method or property |
Cannot use $this |
Because it doesn’t depend on an object |
Good for | Utility, math, logging, helpers |