2

I need to have a static constructor. I was always wondering why there is no support for this functionality.

I need to run a function once when the class is loaded, currently the way I've seen it done is just include a bunch of code in the file after the class declaration. That kinda works until you need to modify protected or private members of the class, then you would need to define a function on the class itself then call it from down there which all gets the job done but seems hacky to me.

What I went ahead and did was in my loader class after the include statement I added this little bit:

if (method_exists($class, 'onLoad')) {
    $class::onLoad();
}

I am having my doubts about that, though, because there may be quite a number of classes included in a request. And this is on each request, so eventually this may add up to some processor time - which leads me to the question I want to ask, since not many classes will even have an onLoad method:

Would you consider this to be a reasonable addition to my framework?

EDIT: Regarding the suggested possible duplicate question - I am not asking for singleton this is not a static class it can be instantiated freely.

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • I doubt that there'll ever be a "static constructor" because it's a contradiction in terms.... the constructor, by definition, is code that is executed on instantiation, so it can never be static – Mark Baker Aug 19 '15 at 23:05
  • possible duplicate of [PHP Static class initializer](http://stackoverflow.com/questions/3312806/php-static-class-initializer) – maxpovver Aug 19 '15 at 23:07
  • The need to run code on class loading is a sign that your class violates the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle). – axiac Aug 19 '15 at 23:12
  • @axiac I need to have a function return value as a static parameter to the class, is that violating? – php_nub_qq Aug 20 '15 at 05:30
  • 1
    It's difficult to appreciate without seeing the code. If you need to call a class static method in order to initialize some static properties before using the class then I think the static method(s) and properties belong to a different class that is a [factory](https://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29) for this class. The static properties are the (non-static) properties of the factory class, the static method is the constructor of the factory class. You first instantiate the factory then use it to create the objects you need. – axiac Aug 20 '15 at 08:54

1 Answers1

6

There's no reason your "SomeClass.class.php" file can't look like this:

class SomeClass {
    public static function onLoad() {
        // ...
    }
    // ...
}

SomeClass::onLoad();

Whether or not this is a Good Idea is up for debate, but I don't see anything overly wrong with initialisation code added in this way to the class file.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592