Static Methods in PHP


In this tutorial, we will learn about Static Methods in PHP. As we know to call any method of class we must create an object of that particular class first. But we can call a static method without creating an object of the class. Creating a static method is easy as creating an instance method expect we write a static keyword before the function keyword.

Please check out the following example program to know how to declare a static method in PHP.

Defining Static Method Example Program:

<?php
class Example{
  public static function hello() {
    echo "Hello, How are you?";
  }
}
?>

to access these static methods we use double colon (::) operators.

Accessing Static Method Example Program:

<?php
class Example{
  public static function hello() {
    echo "Hello, How are you?";
  }
}

// Calling to a static method
Example::hello();
?>

We can access static method in other classes also but static method should be defined with public access.

In many situations when you need to fetch static method in the same class in this kind of scenario you can use the self keyword. Please check out the following example program.

Accessing Static Method in Same Class:

<?php
class Example{
  public function __construct(){
     // Calling to a static method using self keyword
     self::hello();
  }
  public static function hello() {
    echo "Hello, How are you?";
  }
}

$obj =new Example;
?>

In case you want to fetch a static method from the Parent class you can use the parent keyword.

Accessing Static Method from Parent Class:

<?php
class Example{
  public static function hello() {
    echo "Hello, How are you?";
  }
}

class Child extends Example{
   public function __construct(){
     // Calling to a static method using parent keyword
     parent::hello();
  }
}

$obj =new Child;
?>

 



Spread the love:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share