Search code examples
phpstatic-initializer

How should I make up for the lack of static initializers in PHP?


I'm thinking about putting every class into a separate file and doing the static initialization outside of the class definition.

The problem with this is the fact that the initialization will happen before the said class is actually needed (it will happen when the file which contains the class is included for the first time). It's a problem, because it may happen that the class won't be used at all, hence the initialization is unnecessary. And I think the practice of including the used files not in the beginning of your code is simply a dirty technique.

If anybody has a viable solution to this problem, I would greatly appreciate it.


Solution

  • You might look up for __autoload when a class is not found it is called and supposed to include the file contains that class. You can put static initializers in that function.