Static class initializer in PHP Static class initializer in PHP php php

Static class initializer in PHP


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 thisSingleton::someMethod1();// You'd do thisSingleton::getInstance()->someMethod1();


// file Foo.phpclass Foo{  static function init() { /* ... */ }}Foo::init();

This way, the initialization happens when the class file is included. You can make sure this only happens when necessary (and only once) by using autoloading.


Actually, I use a public static method __init__() on my static classes that require initialization (or at least need to execute some code). Then, in my autoloader, when it loads a class it checks is_callable($class, '__init__'). If it is, it calls that method. Quick, simple and effective...