Skip to content
Related Articles

Related Articles

Improve Article

How to create static classes in PHP ?

  • Last Updated : 22 Jul, 2021

A class is a user-defined data type that holds its own data members and member functions that can be accessed and used by creating one or more instances of that class. Every time a class is instantiated, the values that it holds are different and unique to the particular instance or object and not to that class. Static Classes brings forth a property wherein a class itself holds values that remain the same and aren’t unique. Another property of Static Classes is that we can do the aforementioned without having to create an instance of the class.

How to create a static class? 
It’s fairly simple. The variables and methods that are declared and defined within a class are to be declared as static with the use of static keyword, so that they can be used without instantiating the class first. 
An important point to note here is that, since this means a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods since these require an instance of the class.

To access the static class and it’s method use the following syntax:  

 ClassName::MethodName();

Example 1: The following code returns the current date without instantiating the class Date. In this case, the format of the date and not the actual date remains the same.

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());
?>
Output:
April 30th, 2020
2020/04/30 10:48:36

Example 2: The following code checks whether the string is valid or not. It is valid if it’s length is equal to 13. 

PHP




<?php
 
class geeks {
 
    public static $x = 13;
 
    public static function isValid($s) {
        if(strlen($s) == self::$x )
            return true;
        else
            return false;
    }
}
 
$s1 = "geeksforgeeks";
if(geeks::isValid($s1))
    echo "String is valid! \n";
else
    echo "String is NOT valid! \n";
 
$s2 = "geekforgeek";
 
if(geeks::isValid($s2))
    echo "String is valid!\n ";
else
    echo "String is NOT valid! \n";
?>

Output: 

String is valid!
String is NOT valid!

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :