Patrick Schaaf wrote on 12/03/2015 08:40:
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();
I suspect that most places where this occurs, there are other ways to
eliminate it than adding magic pre-initialisation. If a class has lots
of static methods all depending on some state being initialised, maybe
they just shouldn't be static - they should be instance members of a
Singleton or Dependency Injected object. Or maybe they're accessing
members directly which would be better hidden behind an accessor method
which loads some data and "caches" its result.
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)
This sounds like a job for a Singleton or Dependency-Injected object.
The initialisation is a specific action with its own parameters (which
you're currently grabbing from global configuration).
- 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.
This is the only case that seems valid to me: enums and other types of
"computed constant", where the class is just there as a container.
- 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.
The question is, why is this whole hierarchy static? If these were
instances not definitions, the initialisation is a well-defined event
(the constructor), and you can check validity there.
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php