Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static
keyword:
<?php
class
ClassName {
public static function
staticMethod() {
echo "Hello World!";
}
}
?>
To access a static method use the class name, double colon (::), and the method name:
ClassName::
staticMethod();
Let's look at an example:
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
?>
Try it Yourself »
Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).
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 (::):
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
public function __construct() {
self::welcome();
}
}
new greeting();
?>
Try it Yourself »
Static methods can also be called from methods in other classes. To do this, the static method should be public
:
<?php
class A {
public static function welcome() {
echo "Hello World!";
}
}
class B {
public function message() {
A::welcome();
}
}
$obj = new B();
echo $obj -> message();
?>
Try it Yourself »
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
.
<?php
class domain {
protected static function getWebsiteName() {
return "91xjr.com";
}
}
class domainW3 extends domain {
public $websiteName;
public function __construct() {
$this->websiteName = parent::getWebsiteName();
}
}
$domainW3 = new domainW3;
echo $domainW3 -> websiteName;
?>
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!