Normally, to use a method inside a class, you first have to create an object using the new keyword.
However, Static Methods can be called directly on the class itself, without creating an instance of the class first.
Static methods are declared with the static keyword. To access a static method, use the class name, double colon ::, and the method name.
<?php
class Greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method directly without instantiation!
Greeting::welcome();
?>
Static methods are frequently used for Utility classes or Helper functions. For example, a Math::add(a, b) function doesn't really need its own isolated object state to do its job. It just takes inputs and returns an output.
self KeywordIf you want to call a static method from inside another method in the same class, you cannot use $this->. The $this keyword relies on an object existing.
Instead, you must use the self keyword: self::welcome();