Static Method in PHP

Last updated on March 26, 2023

The static method can be directly called through Scope Resolution Operator (::), which means there is no need to create an instance of the class. The static method declares with the static keyword in the class. It can be accessible inside the class through the self keyword, you can’t access it using $this keyword.

Syntax

class YourClassName{
    public static function methodName()
    {
        return "anything...";
    }
}

Usage

Let’s create a class with a static method to understand how it works.

// create a car class with the static color method
class Car{
    public static function color(){
        return "red";
    }
}

In the above example, we have a car class that has a color method with a static keyword. It simply returns the string that is red, to call it outside of class we need to use the scope resolution operator (::).

// call the static color method
echo Car::color();
// Output: red

Call Static Method Within Class

The static methods are accessible in both static and non-static methods. You can call a static method within a call by using the self keyword. Look at the below example,

class Car{
    public static function color(){
        return "red";
    }
    
    public static function body()
    {
        $response = self::color();
        return $response;
    }
}

echo Car::body();
// Output: red

In the above example, we added one more body() method into the Car class. In the new body() method we are accessing the color() method through the self keyword.

Advantages

  • You directly use it without creating a class instance.
  • The static methods are accessible anywhere in the code.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: PHP, PHP-OOP,