Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 303
user258626 Avatar asked Jul 22 '10 19:07

user258626


People also ask

What is static class in PHP?

Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).

What is static method in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

Can you initialize a static class?

A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced.

How do you initialize a class in PHP?

A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!


1 Answers

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(); 
like image 193
Peter Bailey Avatar answered Oct 02 '22 14:10

Peter Bailey