Skip to main content

PHP - Static Methods

The static keyword is how you create static methods and properties.

What makes a static method special is that you can call it directly, with no need to make an instance of its class.


Declare a Static Method

Adding a static method to a class takes one extra keyword, static:

Static method declaration syntax

The static keyword goes ahead of the function name in the declaration:

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

Access a Static Method

Calling a static method takes three parts: first the class name, then a double colon (::), and finally the method name.

The next example declares a static method called welcome() and calls it in exactly that form. Notice that no object is ever created:

Example

Call a static method through its class name:

Prompt
Create a PHP class called greeting with a static method welcome() that echoes "Hello World!". Call the static method directly using the class name without creating an instance.
Output: PHP script

Example

Here, a static method sum() is declared and then called in the same form: class name, ::, method name:

Prompt
Create a PHP class called calc with a static method sum() that takes two parameters and returns their product. Call it with 6 and 4, then echo the result.
Output: PHP script

Static method access syntax

The general form of a static method call:

index.php
<?php
ClassName::staticMethod();
?>

PHP - More on Static Methods

Static and non-static methods can live side by side in a class. To reach a static method from another method of the same class, write self and a double colon (::) before its name:

Example

Here, the constructor calls a static method of its own class through self:

Prompt
Create a PHP class called greeting with a static method welcome() that echoes "Hello World!" and a constructor that calls the static method using the self keyword.
Output: PHP script

Example

A method in another class can call a static method as well, as long as the static method is public:

Prompt
Create two PHP classes: class A with a public static method welcome() that echoes "Hello World!", and class B with a method message() that calls A's static method. Create an instance of B and call message().
Output: PHP script

Example

Inside a child class, call the parent's static method with the parent keyword. In this case, the static method may be either public or protected.

Prompt
Create a PHP class domain with a protected static method getWebsiteName() that returns "PromptCookbook". Then create a child class domainW3 that calls the parent static method in its constructor and stores the result. Echo the website name.
Output: PHP script