Static Methods in PHP
You can call static methods directly, without first making an instance of the class.
The static keyword is used to declare a static method:
Syntax
<?php
class ClassName {
public static function methodName() {
echo “Static method!”;
}
}
?>
Use the class name, a double colon (::), and the method name to call a static method:
Syntax
ClassName::staticMethod();
Example
<!DOCTYPE html>
<html>
<body><?php
class Welcome {
public static function message() {
echo “Welcome to coderazaa”;
}
}// Call static method
Welcome::message();
?></body>
</html>
Output
Welcome to coderazaa
More on Static Methods in PHP
A class can have both methods that are static and those that are not. A method in the same class can use the self keyword and a double colon (::) to call a static method:
Example
<!DOCTYPE html>
<html>
<body><?php
class welcome {
public static function message() {
echo “Welcome to coderazaa”;
}
}class StudentClass {
public function message2() {
welcome::message();
}
}
?>
</body>
</html>
Output
Welcome to coderazaa