Is it possible to create static classes in PHP (like in C#)?

aleemb picture aleemb · Jan 22, 2009 · Viewed 112.3k times · Source

I want to create a static class in PHP and have it behave like it does in C#, so

  1. Constructor is automatically called on the first call to the class
  2. No instantiation required

Something of this sort...

static class Hello {
    private static $greeting = 'Hello';

    private __construct() {
        $greeting .= ' There!';
    }

    public static greet(){
        echo $greeting;
    }
}

Hello::greet(); // Hello There!

Answer

Greg picture Greg · Jan 22, 2009

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
        if (self::$initialized)
            return;

        self::$greeting .= ' There!';
        self::$initialized = true;
    }

    public static function greet()
    {
        self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>