How to Generate Static Classes in PHP

The methods and variables, defined and declared inside a class should be declared as static using the static keyword in order to be used without the initial instantiating of the class.

As a class variable can be accessed without a particular instance, there will be merely a single version of the variable. Also, note that non-static variables can’t be accessed by a static method. An instance of a class is required for such methods.

Here, we will figure out how to generate static classes in PHP.

Generating Static Classes

For accessing the static class and its method, the following syntax is used:

ClassName::MethodName();

Let’s consider several examples.

Example 1

Here, we will see a code that is capable of returning the current date without the instantiation of the class Date.

The date format and the actual date remain the same.

<?php

class Date
{
  public static $date_format1 = 'F jS, Y';
  public static $date_format2 = 'Y/m/d H:i:s';
  public static function format_date($unix_timestamp)
  {
    echo date(self::$date_format1, $unix_timestamp), "\n";
    echo date(self::$date_format2, $unix_timestamp);
  }
}

echo Date::format_date(time());

?>

The output will look as follows:

  April 30th, 2020
  2020/04/30 10:48:36

Example 2

In the example below, we will check if a string is valid. If the length is 13, then it is considered valid.

<?php

class w3
{
    public static $x = 13;

    public static function isValid($s)
    {
        if (strlen($s) == self::$x) {
            return true;
        } else {
            return false;
        }
    }
}

$s1 = "w3d1234567890";
if (w3::isValid($s1)) {
    echo "String is valid!\n";
} else {
    echo "String is NOT valid!\n";
}

$s2 = "w3docs";

if (w3::isValid($s2)) {
    echo "String is valid!\n ";
} else {
    echo "String is NOT valid! \n";
}

?>

The output will show:

  String is valid!
  String is NOT valid!

About Static Classes

A class is considered a user-defined data type, that is capable of holding its data members and member functions. Those can be accessed and applied by generating one or more class instances.

Each time a class is configured, the values that it keeps are distinct and unique to a specific object or instance, but not to that class.

A static class can produce a property, while a class keeps values that stay the same and are not unique.