Advertisement
Google Ad Slot: content-top
PHP OOP - Static Methods
PHP - Static Methods
In PHP, static methods belong to the class itself, not to a specific object of the class.
You can call a static method without creating an object.
Static methods are declared with the static keyword:
Syntax
class ClassName {
public static function staticMethodName() {
// code
}
}
You call the method using the class name, double colon (::), and the method name::
Syntax
ClassName::staticMethodName();
Let's look at an example:
Explanation:
public static function welcome()→ Declares a static method.Greeting::welcome();→ Calls the method without creating an object.
PHP - More on Static Methods
In PHP, a class can contain both static and non-static methods. Static methods can be accessed from within the same class using the self:: keyword (with the scope resolution operator ::).
In PHP, public static methods can be accessed from outside their class, including from other classes.
In PHP, when you're working with inheritance, you can call a static method from a parent class inside a child class using the parent:: keyword. This works for public and protected static methods.