Skip to content

How to Generate Static Classes in PHP

Methods and variables defined inside a class must be declared as static using the static keyword to be used without instantiating the class first.

Because static variables are accessed without a specific instance, only one copy of the variable exists for the entire class. Also, note that static methods cannot access non-static variables; an instance of the class is required for those.

Here, we will look at how to create classes with static members in PHP. Note that PHP does not support true static classes like some other languages; instead, you declare a regular class and make its properties and methods static.

Generating Static Classes

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

create access classes syntax

php
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 return current date without class Date instantiation

php
<?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());

?>

php return current date without class Date instantiation, output

console
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 check if a string is valid

php
<?php

class Validator
{
  public static $x = 13;

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

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

$s2 = "w3docs";

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

?>

php check if a string is valid, output

console
String is valid!
String is NOT valid!

About Static Classes

A class is a user-defined data type capable of holding data members and member functions. These can be accessed and used by creating one or more class instances.

When a class is instantiated, the values it holds are distinct and unique to each specific object, not to the class itself.

Static properties belong to the class itself rather than to any specific instance. This means they retain the same value across all instances of the class.

In modern PHP, it is common practice to declare classes containing only static methods as final to prevent inheritance and ensure they are used strictly as utility containers.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.