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.
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(::).
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.
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.
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 (__)!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With