Static methods can be called directly without needing an instance of the class (an object). And, $this-> pseudo-variable is not available inside static methods.However, you can access a special variable called self
. The self
variable means the current class.
To access a static method use the class name, double colon (::), and the method name:
ClassName::staticMethod();
The following table illustrates the differences between the self
and $this
:
$this |
self |
---|---|
Represents an instance of the class or object | Represents a class |
Always begin with a dollar ($) sign | Never begin with a dollar($ ) sign |
Is followed by the object operator (-> ) |
Is followed by the :: operator |
The property name after the object operator (-> ) does not have the dollar ($) sign, e.g., $this->property . |
The static property name after the :: operator always has the dollar ($ ) sign. |
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
Let's understand with simple example of using static method :
Output :Hello World!