Re: Class static initialization block

From: Date: Sat, 11 Sep 2021 23:35:41 +0000
Subject: Re: Class static initialization block
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-116032@lists.php.net to get a copy of this message
Hey David, On Sun, 12 Sep 2021, 01:28 David Rodrigues, <david.proweb@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(). > This already works without any magic. In MyClass.php: ```php class MyClass { public static DateTimeImmutable $startup; public function horribleInitializationPractices() { self::$startup = new DateTimeImmutable(); } } MyClass::horribleInitializationPractices(); ``` That's really all there is to it. What you define as hacky is really normal/boring, and does not need special constructs. Also, it's generally not a good idea to sprinkle static mutable runtime-bound all over the place: it should be an exception, not a rule. >

« previous php.internals (#116032) next »