Re: Initializing constants once, with code?
| From: | Mike Schinkel | Date: | Mon, 06 Jan 2020 19:17:10 +0000 |
| Subject: | Re: Initializing constants once, with code? | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-108011@lists.php.net to get a copy of this message | ||
> On Jan 5, 2020, at 5:04 PM, tyson andre <tysonandre775@hotmail.com> wrote:
>
> I have a work in progress wrapper for allowing const-like syntax for global constants
>
static const X = $dynamicExpression;.
> This can be seen in https://github.com/TysonAndre/php-src/pull/100µ,â6f†Å0ˆ
> ]Jõž
Thanks for replying and including this. Nice work.
> - Eagerly initialized dynamic constants are easier to reason about in some ways (e.g. fetching
> the constant of an already fetched class is less likely to cause pauses or exceptions.)
> This makes un-noticed errors in rare code paths less likely.
> - Attempting to support function calls, property accesses, class constant accesses (e.g.
> inherited), and variables in class constants recursively and/or lazily
> would probably break a lot of code/assumptions in the php engine.
Frankly my strong preference would be for on-demand initialization because otherwise each page load
could end up running lots of code to calculate values that are never used on the particular page.
> My preference would be to make it easier to use dynamic expressions, and recommend in coding
> guidelines that
> certain types of expressions "SHOULD NOT" be used for constants that vary on a
> particular host.
> (network calls, time, etc)
>
> ```
> const DEFAULT_PAYLOAD = json_encode(['key' => 'value']);
> const ALLOWED_ELEMENT_TYPES = array_merge(self::FIRST_TYPES, self::SECOND_TYPES);
> const ELEMENT_LENGTHS = array_map('strlen', self::ELEMENTS);
> ```
You and me both.
-Mike