Before moving to static methods let’s see the instance method.
To utilize the class’s methods and properties, you must first construct an object and then use the object to access the class’s methods and properties. These methods and properties are referred to as instance methods and properties because they are tied to a specific instance of the class. Instead of using an object, PHP allows you to use a class to access methods and attributes.
Static methods can be called without having to create a class instance first. The static keyword is used to declare static methods:
Syntax Static Methods
public static function test()
{
// Method implementation
}
They can be called from outside the class using the class name and the scope resolution operator (::), as seen below:
MyClass::test();
Consider the following scenario:
<?php class Message { public static function wlcm() { echo "Welcome to Tutorialsart!"; } } // Call static method Message::wlcm(); ?>
Static Methods: Self Keyword:
Methods can be both static and non-static in a class. The self keyword and double colon (::) can be used to access a static method from another method in the same class.
We’ll call a non-static function in a static function within the same class in the example below:
<?php class helo { public static function staticfunction() { echo "Static function called in non static function"; } public function __construct() { self::staticfunction(); } } new helo(); ?>
Static Methods and Inheritance:
If Static methods are public then they can also be invoked from other class methods. Use the parent keyword inside the child class to invoke a static method(Protected/Public) from a parent class.
Let’s see an example below in which child class is invoking static method of parent class.
<?php class Aparent{ protected static function staticfunction() { return "Tutorilsart"; } } class BChild extends Aparent { public $name; public function __construct() { $name = parent::staticfunction(); echo $name; } } $BChild = new BChild; ?>
In the next chapter, we will learn static properties.