A simple guide to PHP’s static keyword

We’ve seen previously how to instantiate a new object through a class.

We can do that many times and have many instances.

There are many cases where you want to be able to use a property or method of a class in all the objects created from that class and not only in a particular instance.

In order to call a public, protected, or private method, we need to instantiate an object first:

$user = new User();$user->getName();

A static method don’t need that since it can be called directly on the class with the scope resolution operator (::).

User::createGuest();

There is no need to instantiate a User object first.

Static methods

When an action doesn’t depend on a specific object, opt for a static method.

For example, a validation helper:

Code example of an utility function.

This method just checks the value it receives, so it does not need access to a particular object instantiated from the Validator class. The result depends only on its arguments.

Note: A static method cannot use the $this keyword because $this refers to an object.

Static properties

A static property holds a single shared value for the entire class, rather than for individual instances.

Code example of a static property.

Every time you instantiate an object from the Visitor class, the same shared $count value increases. You can access a static property using the class name and the scope resolution operator, the same way you call a static method.

Concluding

Static methods and properties are great for counters and small utility functions.

A utility function in PHP is a reusable piece of code that simplifies common programming tasks. These functions help developers avoid repetitive code.

Static methods and properties are preferred for cases where data is shared between all objects.

However, they aren’t the best choice when an action relies on changing data within a specific object. In such cases, it’s better to create an object and use a normal property or method.

Although my blog doesn’t support comments, feel free to reply via email or X.