On Sun, Sep 12, 2021 at 2:28 AM David Rodrigues <david.pro...@gmail.com>
wrote:

> Hello!
>
> I would like to suggest a feature I saw being implemented in the V8 9.4
> engine called "*class static initialization block*".
>
> https://v8.dev/blog/v8-release-94
>
> In short, it is a method that is executed once when a class is imported and
> loaded, allowing for some more advanced initialization process to be done.
>
> class Test {
>     static readonly Carbon $now;
>
>     static () {
>         self::$now = now();
>     }
> }
>
> Currently I can only do this in a very hacky way, usually by creating a
> public static method and calling it after class initialization.
>
> class Test {
>     static Carbon $now;
>
>     public static function init(): void {
>         self::$now = now();
>     }
> }
>
> Test::init();
>
> I think the way the V8 does is much more interesting.
>
> Another alternative would be to create a magic method like __initialize().
>

Hey David,

The first time I built static initializers for classes was about 15 years
ago when, in my class loader (composer was not a thing), if the class had a
static method called __init(), it would call it after loading.
I don't remember why I needed it but I'm pretty sure I was used with the
Java static initialization blocks.
Maybe also the limitations that exist on the static values not being able
to be dynamically defined could have played a role but I mainly blame it on
my lower skill as a programmer.

I have never used it in a similar way in the past 10 years, as far as I
remember.
That's because I almost never use static state as that's just global state
and it should be avoided.

If you really want to compute some static state, I think that's going to be
in PHP in a few years.
An attempt to add it with the new keyword was done in
https://wiki.php.net/rfc/new_in_initializers#unsupported_positions but was
eventually dropped for class static properties and constants. You can read
details about it there.
Once the identified problems will be sorted out and probably the option to
have static initialization blocks will be possible.

So far, the current possible approach with having a public static method
and calling it after class definition works well in most of the cases.
If it's really needed, I think we can use it and be happy that it is
supported on all past PHP versions.

There is only one place that I know where I think it will not work, if the
class is preloaded. But I guess you can just avoid it for now.

Alex

Reply via email to