PHP Static Methods

This tutorial helps you learn about the PHP Static methods.

 

What is PHP Static methods?

Any static method is accessible directly without creating an instance of the class first. Static keywords are used for declaring static methods.

Static methods are declared with the static keyword:

<?php
class ClassName {
  public static function staticMethod() {
    echo "Hello World!";
  }
}
?>

For accessing a static method, you can use the class name, a double colon (::) and the name of the method:

ClassName::staticMethod();

 

Example:

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

// Call static method
greeting::welcome();
?>

Here, you have declared a static method: welcome(). Next, you can call the static method by using the class name, a double colon (::) and the name of the method (without the creation of an instance of the class first).

 

A class may have both static and non-static methods. You can access a static method from a method in the same class by using the self keyword and double colon (::)

Example:

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }

  public function __construct() {
    self::welcome();
  }
}

new greeting();
?>

 

You can also call the static methods from the methods in other classes. For doing this, the static method should be public:

<?php
class greeting {
  public static function welcome() {
    echo "Hello World!";
  }
}

class SomeOtherClass {
  public function message() {
    greeting::welcome();
  }
}
?>

For calling a static method from a child class, you can use the parent keyword inside the child class. In this case, the static method can be public or protected.