PHP - Static Methods
The static keyword is how you create static methods and properties.
What makes a static method special is that you can call it directly, with no need to make an instance of its class.
Declare a Static Method
Adding a static method to a class takes one extra keyword, static:
Static method declaration syntax
The static keyword goes ahead of the function name in the declaration:
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
Access a Static Method
Calling a static method takes three parts: first the class name, then a double colon (::), and finally the method name.
The next example declares a static method called welcome() and calls it in exactly that form. Notice that no object is ever created:
Example
Call a static method through its class name:
Output: PHP script
<?php
class greeting {
// static method
public static function welcome() {
echo "Hello World!";
}
}
// Call static method directly
greeting::welcome();
?>
Example
Here, a static method sum() is declared and then called in the same form: class name, ::, method name:
Output: PHP script
<?php
class calc {
// static method
public static function sum($x, $y) {
return $x * $y;
}
}
// Call static method
$res = calc::sum(6, 4);
echo $res;
?>
Static method access syntax
The general form of a static method call:
<?php
ClassName::staticMethod();
?>
PHP - More on Static Methods
Static and non-static methods can live side by side in a class. To reach a static method from another method of the same class, write self and a double colon (::) before its name:
Example
Here, the constructor calls a static method of its own class through self:
Output: PHP script
<?php
class greeting {
// static method
public static function welcome() {
echo "Hello World!";
}
// non-static method
public function __construct() {
self::welcome();
}
}
new greeting();
?>
Example
A method in another class can call a static method as well, as long as the static method is public:
Output: PHP script
<?php
class A {
public static function welcome() {
echo "Hello World!";
}
}
class B {
public function message() {
A::welcome();
}
}
$obj = new B();
echo $obj -> message();
?>
Example
Inside a child class, call the parent's static method with the parent keyword. In this case, the static method may be either public or protected.
Output: PHP script
<?php
class domain {
protected static function getWebsiteName() {
return "PromptCookbook";
}
}
class domainW3 extends domain {
public $websiteName;
public function __construct() {
$this->websiteName = parent::getWebsiteName();
}
}
$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>