On Thursday 12 March 2015 00:10:15 Rowan Collins wrote:
> On 11/03/2015 23:21, Johannes Ott wrote:
>
> > 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...
It's useful everywhere you now have more than one method starting
if (!static::$is_initialized) static::initialize_me();
Some examples from our codebase:
- a session wrapper class, hiding $_SESSION behind setter/getter methods,
where the static class initialization determines which cookie to use,
depending on some global feature flags, and which session backend to use,
depending on current availability. (main purpose, apart from clean calling
side code just using the setters/getters, is to get the lazy_write
functionality Yasuo tried to introduce recently)
- computation of some class properties from others, like doing an array_flip
on one to get a reverse mapping.
- definition of computed constants, in various places. Partly obsolete now
that class constants support constant expressions, but needed as soon as these
are not really constant.
- setting up some class properties used by various methods, that should depend
on some global feature flags (defined by the users of the class, usually
toplevel scripts)
- invariant checks on subclasses, in various places, where concrete subclasses
set up some static properties of a configuration nature, and I want to make
sure in the base class, as early as possible, that the values are consistent
and make sense, avoiding checks spread all over the place in various methods.
Of course, most of this could be done by code outside the class definition, in
the same file. But that has proven, in the past, a fountain of joy wrt.
placement, with variations needed for APC and opcache, and general frustration
all around.
best regards
Patrick
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php