Re: static constructor

From: Date: Thu, 12 Mar 2015 12:32:44 +0000
Subject: Re: static constructor
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-84634@lists.php.net to get a copy of this message
Johannes Ott wrote on 12/03/2015 08:54:
Am 12.03.2015 um 05:17 schrieb Levi Morrison:
On Wed, Mar 11, 2015 at 6:10 PM, Rowan Collins <rowan.collins@gmail.com> wrote:
On 11/03/2015 23:21, Johannes Ott wrote:
So now I want to do my first own proposal for a new function in PHP and I hope doing it right with starting a discussion here first. The purpose of this suggestion is to introduce a static constructor, which is called before the first call to class either static or non-static to initialize some static properties which are needed by the class.
Can you give an example use case for when this would be useful? I'm struggling to think of one for which there isn't already an established coding pattern...
Notably, user-land enums. You don't want public constructors because you don't want it instantiated except for each enum property. You also need it to run on class creation, not afterwards. I think we'd be better off adding language-level enums than static constructors though.
Yes indeed user-land enums are one of the use cases I use this feature at the moment. But there some other use cases as well:
Most of these examples are just crying out to be real objects, not static classes. You might not want to be creating them every time you use them, but that's what patterns like Singletons and Dependency Injection are for.
1. Nearly all of my classes have a static LogAdapter $LOG which has to be intialized with Classname once. class A {
     private static $LOG;
     public static function __static() {
         self::$LOG = LogAdapter::getLogger(self::class);
     }
} A::__static(); The LogAdapter by it selfs although have a __static() method to prepare the Log4PHP-Framework I'm using.
This particular example could be achieved with a static getLogger() method, which does the initialisation check the first time the logger is needed, rather than the first time class A is needed. To my mind, the creation of a class in memory should not have side-effects - you should be able to assume that all your classes exist at the same time, before any of your code runs. The only justification for not acting that way would be Python-style metaclasses, where the creation of a class definition was the responsibility of some other object, and that's a power to be wielded very carefully. Regards, -- Rowan Collins [IMSoP]

« previous php.internals (#84634) next »