PHP - Static Methods
The static keyword is used to create static methods and properties.
Static methods can be accessed directly - without creating an instance of the class first.
Declare a Static Method
To add a static method in a class, use the static keyword:
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
Access a Static Method
To access a static method, specify the class name, followed by a double colon (::) and the method name:
ClassName::staticMethod();
In the following example, we declare a static method: welcome(). Then, we access the static method directly by using the class name, a double colon (::), and the method name (without creating an instance of the class first):
Example
<?php
class
greeting {
// static method
public static function
welcome() {
echo "Hello World!";
}
}
// Call static method directly
greeting::welcome();
?>
In the following example, we declare a static method: sum(). Then, we access the static method directly by using the class name, a double colon (::), and the method name:
Example
<?php
class calc {
// static method
public static
function sum($x, $y) {
return $x * $y;
}
}
// Call static method
$res = calc::sum(6, 4);
echo $res;
?>
PHP - More on Static Methods
A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::):
Example
<?php
class greeting {
// static method
public static function welcome() {
echo "Hello World!";
}
// non-static
method
public function __construct()
{
self::welcome();
}
}
new
greeting();
?>
Static methods can also be called from methods in other classes. To do this, the static method should be public:
Example
<?php
class
A {
public static function
welcome() {
echo "Hello World!";
}
}
class
B {
public function
message() {
A::welcome();
}
}
$obj = new B();
echo $obj ->
message();
?>
To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected.
Example
<?php
class domain {
protected static function
getWebsiteName() {
return "example.com";
}
}
class domainW3 extends domain {
public $websiteName;
public function __construct() {
$this->websiteName =
parent::getWebsiteName();
}
}
$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>