phpclassstaticconstructorinitializer

Static class initializer in PHP


I have an helper class with some static functions. All the functions in the class require a ‘heavy’ initialization function to run once (as if it were a constructor).

Is there a good practice for achieving this?

The only thing I thought of was calling an init function, and breaking its flow if it has already run once (using a static $initialized var). The problem is that I need to call it on every one of the class’s functions.


Solution

  • Sounds like you'd be better served by a singleton rather than a bunch of static methods

    class Singleton
    {
      /**
       * 
       * @var Singleton
       */
      private static $instance;
    
      private function __construct()
      {
        // Your "heavy" initialization stuff here
      }
    
      public static function getInstance()
      {
        if ( is_null( self::$instance ) )
        {
          self::$instance = new self();
        }
        return self::$instance;
      }
    
      public function someMethod1()
      {
        // whatever
      }
    
      public function someMethod2()
      {
        // whatever
      }
    }
    

    And then, in usage

    // As opposed to this
    Singleton::someMethod1();
    
    // You'd do this
    Singleton::getInstance()->someMethod1();