Re: Re: Straw poll: Places to allow function calls in constant expressions

From: Date: Wed, 19 Feb 2020 19:21:46 +0000
Subject: Re: Re: Straw poll: Places to allow function calls in constant expressions
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-108687@lists.php.net to get a copy of this message
> On Feb 19, 2020, at 2:00 PM, Bishop Bettini <bishop@php.net> wrote: > > Consequently, the only way to safely initialize class constants and static > members is at run-time, and I can only think of one way to do it. Apologies > if this has already been suggested: taking a cue from C#, a static class > constructor ([1]) would allow us to have expression-initialized constants > and static members. > > <?php > class Config { > public const URL = null; // compile time initialization > protected static $mtime = null; // compile time initialization > private static function __constructStatic() { > $env = json_decode(file_get_contents('config.json')); > self::URL = $env->url; > self::$mtime = filemtime('config.json'); > } > public function reload() { > if (self::$mtime < filemtime('config.json')) > self::__constructStatic(); > } > } > } > > echo Config::URL; // assert: runtime has already called _constructStatic > $config = new Config; // assert: __constructStatic called only once by > runtime > $config->reload(); // instance may call its own static constructor > ?> > > Trying to do the same for global constants, static variables, or function > default parameters resists a similar initialization mechanism because we > don't have defined common entry point analogues. If we had a main(), or if > we had framed @before decorators, we could do something similar, but we > don't -- so I feel we should leave these off the table. For different reasons than this RFC I have wanted a static class constructor for a really long time. I hope this is something we can seriously consider. Thanks Bishop for proposing it. -Mike

« previous php.internals (#108687) next »