Static Methods and Static Properties are used when we call out a method or properties but don’t want to bother creating an object for it.
As we all know to run a particular method or get the value of properties we first have to create an object of that class.
But in the case of Static Properties or methods, this ain’t true.
Static Methods in PHP
To call any method we have to first create an object of the class where that method is.
But the Static methods can be called directly without creating an instance of the class first.
These methods are created using keyword static
Here is the syntax for creating a static method-
class ClassName{
public static function staticMethod(){
echo "Hello World!";
}
}
And to call a static method we have to use a double colon (::) and the name of that static method-
ClassName::staticMethod();
How to Create static methods with Examples
As you have already learned that to create a static method we use the static keyword before the function keyword.
And to the callback that method following the class name we use the double colon and the name of the static method.
Here is the simplest example of the static method-
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
Using the Static methods in class along with normal methods
A class could contain both static and non-static methods.
However, to create an object would be a little bit different.
For example, we can access the static method even inside a class using the self keyword.
In this way when we call using an object the static methods would call automatically.
To achieve this we put this kind of method inside a constructor so it would call automatically when the object of that class is called.
Here is how we can do this-
class greeting {
public static function welcome() {
echo "Hello World!";
}
public function __construct() {
self::welcome();
}
}
new greeting();
Static Properties in PHP
Similar to methods, static properties can be also called directly without creating an instance of a class.
Static properties are declared using static
keywords before the variable name and after its access modifier.
Here is the syntax for creating static properties in PHP-
class ClassName {
public static $staticPropName = "rahulbodana.com";
}
and to access this static property we use a double colon followed by name of the class and static property-
ClassName::$staticPropName;
Similar to methods by returning the static method using the self keyword inside the class we can return its value with the Object of that class.
Tags: static method in PHP, static members in PHP, static class in PHP, static variable in PHP w3schools, a static variable in PHP with the example, PHP static constructor.