Jan Brinkmann
By Jan Brinkmann Last updated on Shown in: php 7

Imagine you need a helper function that always formats names the same way, and this function shouldn't need to know anything about a specific object. That's exactly what static methods are for in PHP. They don't belong to a single instance, but to the data type, that is, to the class itself. You call them directly via the class name, without having to create an object first.

Object-oriented web programming with php - 5.08 Static methods

The video is only loaded from YouTube when you play it – data (including your IP address) is then transmitted to YouTube/Google. More in the privacy policy

In this tutorial, you will develop a small class for name formatting step by step. Along the way, you'll see why an instance is superfluous here, how the double colon operator works, and where static methods reach their limits.

Key Takeaways

  • Static properties and methods belong to the class. There is only one value for the entire data type and no individual values per object.
  • Access is done via the double colon operator, i.e. ClassName::method().
  • A static method doesn't need an object. This saves effort when you don't need any instance variables.
  • There is no $this in a static method. Instead, you access values of the class with self::.
  • Calling normal methods statically is deprecated and should be avoided.

Step-by-Step Guide

Step 1: The Basic Idea of Static Members

So far, you have learned that properties and methods are attached to an instance. Static members work differently. When you mark a property or method as static, it belongs to the data type. This is comparable to a constant that is the same for all objects. You access it by using the class name with the double colon operator.

Static methods in PHP: calling directly via the class

Step 2: Creating a Class for Name Formatting

As an example, you create a class Formatter. Its task is to bring values into a specific format. To start, you write a method namensformatierung that takes a first name and a last name. With sprintf, you build a string in the format "Name: Last name, First name" and return it.

class Formatter {
    public function namensformatierung($vorname, $nachname) {
        return sprintf("Name: %s, %s", $nachname, $vorname);
    }
}

The idea isn't wrong, but it has a catch, which you'll see in the next step.

Step 3: Recognizing the Instance as an Unnecessary Detour

So far, you have to create an object first for every call. It looks like this: $format = new Formatter(); and then echo $format->namensformatierung("Jan", "Bringmann");. This works, but it is unnecessarily cumbersome. The method doesn't use any properties of the object. It works exclusively with the passed parameters. So an instance serves no purpose here.

Static methods in PHP: calling directly via the class

Step 4: Checking the Output in the Browser

You save the file and open it in the browser. The text "Name: Bringmann, Jan" appears there. The advantage of this construction becomes apparent at the latest when you want to change the format. The formatting is centralized in one method. Whether you call it once or a hundred times, you only change the code in one place.

Static methods in PHP: calling directly via the class

Step 5: Adjusting the Format Centrally

Let's assume that in the future you want to output first name and last name in the order "First name Last name" or use a semicolon as a separator. You change the sprintf string exactly once, and all calls in the project automatically adopt the new representation. Especially in larger applications, this principle is worth its weight in gold, because you avoid errors caused by forgotten places.

Step 6: Declaring the Method as Static

Now comes the actual step. Since the method doesn't use any instance values, you can mark it as static. To do this, you add the keyword static before function. The declaration then reads public static function namensformatierung(...). In this small example, you don't notice a difference at first, because PHP isn't as strict when you simply call it via an object.

Step 7: Trying Out the Direct Call via the Class

Now you call the method without an object: echo Formatter::namensformatierung("Jan", "Bringmann");. The double colon operator shows you that you are accessing the data type directly. By the way, the class name can also be stored in a variable, for example $classname = "Formatter";. With $classname::namensformatierung(...) you achieve the same result. What matters is that no object is created.

Step 8: Understanding the Call of Normal Methods as an Error

In PHP, you can also call a non-static method via the class name. This was possible in older versions, but was marked as deprecated with PHP 5.4. In current PHP versions, the call results in an error. Therefore, you should declare every method that is called this way as static from the start. This way you work cleanly and are prepared for future versions.

Static methods in PHP: calling directly via the class

Step 9: Recognizing the Problem with Instance Variables

It gets interesting when the class has a property, for example public $format = "Name: %s, %s";. If you try to access it in a static method with $this->format, you get an error. The reason is simple: when calling via the class name, no instance exists, and therefore no $this either. The method has no access to instance variables.

Static methods in PHP: calling directly via the class

Step 10: Accessing Class Values with self

The solution is to declare the property as static as well, i.e. public static $format = "Name: %s, %s";. Within the class, you then access it with self::$format. The keyword self refers to the current scope, that is, to the class and not to an instance. This makes access work in a static method too. You can now define the formatting in one place and still work without an object.

Summary – Static Methods in PHP: Calling Directly via the Class

Static methods and properties belong to the class and not to an instance. You call them directly with the double colon operator. This makes sense when a method does not need any object values, as with a central name formatting. Within a static method, you have no access to $this, but use self:: for class values. Normal methods should not be called statically because that is deprecated. Therefore, declare your methods correctly from the start.

FAQ

When is it worth using a static method?A static method is worthwhile when it only works with passed parameters and does not need any properties of an instance. Helper functions such as formatting are a typical example.

Why can't I access $this in a static method?When calling via the class name, no object is created. Therefore, there is no reference to an instance, and $this is not available.

What does self mean in a static method?The keyword self refers to the current class. With self::$property or self::method() you access static members of your own class.

May I call a normal method via the class name?You should not do that. In older PHP versions it was possible, but it was marked as deprecated. In current versions, the call results in an error.

274
Jan Brinkmann
Trainer About Jan Brinkmann Web development with passion! Jan has been a developer for over 15 years. All courses by Jan Brinkmann