What is the PHP static method?

Overview

A method is simply a code block that carries out certain functions and can be called or reused. A static method is a function that resides inside a class and is declared using the static keyword.

In the static method, we don’t need to create an instance of the class before accessing the method. Let’s see an example:

Example

<?php
/* Use static */
class speak {
public static function opinion() {
echo 'Educative is the Best';
}
}
speak::opinion();

Code explanation

To use an object in a class, we need to instantiate the class using the new keyword. However, we don’t need to instantiate the speak class to access a static method. As seen above, we just need to call the class and access the static method using the ::.

  • Line 4: We create a class, speak.
  • Line 6: We create the static method, opinion(), using the static keyword whose access modifier is public.
  • Line 7: We print the output, "Educative is the best."
  • Line 11: We then access the speak::opinion() method that executes the opinion() method. This prints the output.

Free Resources