PHPOOP - Static Methods
PHP - Static Methods
Thestatic 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 thestatic keyword:
classClassName {
public static functionstaticMethod() { 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
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
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 theself keyword and double colon (::):
Example
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 bepublic:
Example
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 theparent keyword inside the child class. Here, the static method can bepublic orprotected.
Example
class domain {
protected static function getWebsiteName() {
return "W3Schools.com";
}
}
class domainW3 extends domain {
public $websiteName;
public function __construct() {
$this->websiteName = parent::getWebsiteName();
}
}
$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>

