LearnStatic methods and properties

Static methods and properties

In certain cases, it is better to approach methods and properties of a class without the need to create an object out of the class. This can be achieved by defining the methods and properties of a class as static. Even though the use of static methods and properties is considered a bad practice, there are cases in which their use is quite handy and justified.

In certain cases, it is better to approach methods and properties of a class without the need to create an object out of the class.

We have already learned about the three access modifiers called public, protected and private. This tutorial is devoted to the fourth modifier, static, that allows access to classes' properties and methods without the need to create objects out of the classes.

How to define methods and properties as static?

In order to define methods and properties as static, we use the reserved keyword static. In the following example, the class Utilis has a static public property with the name of $numCars and so the variable name is preceded by both the static and the public keywords.

class Utilis {
  // static methods and properties are defined with the static keyword.
  static public $numCars = 0;
}

How to approach static methods and properties?

In order to approach static methods and properties we use the scope resolution operator (::). In the example given below, in order to work with the static property of $numCars, we use the following code:

// set the number of cars
Utilis::$numCars = 3;
 
// get the number of cars
echo Utilis::$numCars;

Result:
3

Pay attention to the use of the $ sign right after the scope resolution operator.

How to approach the static methods from within the class?

In the same manner that we used the $this keyword to approach the class's own properties and methods from within the class, we use the reserved keyword self to approach static methods and properties.

In the example given below, the method addToNumCars() gets and sets the number of cars from the static $numCars property within the same class by using the self keyword.

class Utilis {
  static public $numCars = 0;
 
  static public function addToNumCars($int)
  {
    $int = (int)$int;
    self::$numCars += $int;
  }
}

Now, we can use the code we have written so far to set and get the number of cars.

echo Utilis::$numCars;
 
Utilis::addToNumCars(3);
echo Utilis::$numCars;
 
Utilis::addToNumCars(-1);
echo Utilis::$numCars;

Result:
0
3
2

When to use static properties and methods?

The main cases in which we consider the use of static methods and properties are when we need them as counters and for utility classes.

The use of static properties and methods is considered to be a bad practice. However, in some cases, the ability to use a property or a method without the need to create an object can be advantageous. The main cases in which we consider the use of static methods and properties are when we need them as counters and for utility classes.

Use case 1: as counters

We use static properties as counters since they are able to save the last value that has been assigned to them. For example, the method add1ToCars() adds 1 to the $numberOfCars property each time the method is called.

class Utilis {
  // Hold the number of cars.
  static public $numberOfCars = 0;
 
  // Add 1 to the number of cars each time the method is called.
  static public function add1ToCars()
  {
    self::$numberOfCars++;
  }
}
 
echo Utilis::$numberOfCars;
 
Utilis::add1ToCars();
echo Utilis::$numberOfCars;
 
Utilis::add1ToCars();
echo Utilis::$numberOfCars;
 
Utilis::add1ToCars();
echo Utilis::$numberOfCars;

Result:
0
1
2
3

Use case 2: for utility classes

It is very common to use static methods for utility classes. The sole purpose of utility classes is to provide services to the main classes. Utility methods can perform all kinds of tasks, such as: conversion between measurement systems (kilograms to pounds), data encryption, sanitation, and any other task that is not more than a service for the main classes in our application.

The example given below is of a static method with the name of redirect that redirects the user to the URL that we pass to it as an argument.

class Utilis {
  // The method uses PHP's header function to redirect the user.
  static public function redirect($url)
  {
    header("Location: $url");
    exit;
  }
}

In order to use the redirect() method, all we need to do is call it from the scope of the Utilis class without having the need to create an object. It's as simple as this:

Utilis::redirect("http://www.phpenthusiast.com");

Why static should be used with caution?

Whenever you use static, be sure to use it for utilities and not for convenience reasons.

If you are considering the use of static methods and properties because they are convenient and can be approached without the need to first create an object, please be cautious, because static methods suffer from the following two major disadvantages:

  1. You will have a hard time performing automated testing on classes that use static methods.
  2. Static methods and variables present globals to the code that can be approached from anywhere. This is something that we should try to avoid as much as possible.

So, whenever you use static, be sure to use it for utilities and not for convenience reasons.

Conclusion

In this tutorial, you have learned how and when to use static methods and variables, and why you should use them with much cautious. Click here to practice the subject. You can get all of the tutorials by buying The essentials of Object Oriented PHP eBook for 4.99$.

comments powered by Disqus