Re: [RFC] Static Constructor

From: Date: Thu, 20 Jun 2024 08:57:09 +0000
Subject: Re: [RFC] Static Constructor
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Wed, Jun 19, 2024 at 11:57 PM Mike Schinkel <[email protected]> wrote:

> On Jun 19, 2024, at 2:36 PM, Ilija Tovilo <[email protected]> wrote:
> On Wed, Jun 19, 2024 at 2:34 PM Erick de Azevedo Lima
> <[email protected]> wrote:
>
> New expressions continue to not be supported in (static and non-static)
> property initializers and class constant initializers. The reasons for this
> are twofold:
> [snip]
> For static property initializers and class constant initializers a
> different evaluation order issue arises. Currently, these initializers are
> evaluated lazily the first time a class is used in a certain way (e.g.
> instantiated). Once initializers can contain potentially side-effecting
> expressions, it would be preferable to have a more well-defined evaluation
> order. However, the straightforward approach of evaluating initilizers when
> the class is declared would break certain existing code patterns. In
> particular, referencing a class that is declared later in the same file
> would no longer work.
>
>
> Lazy evaluation might be ok if order is clearly defined.
>
>
> Consider that some uses for a static function need to always occur no
> matter whether or not any other method of the class is called. My previous
> email [1] covered several.
>
> Here [2] is a discussion on StackOverflow of "hooks" that should be
> eagerly loaded.
>
> Thus I think it important that if lazy evaluation is used for static
> initializers then it should be an option, and ideally one that is opt-in
> vs. opt-out, e.g.:
>
> class Foo {
>     private static lazy function __staticConstruct():void {
>         // Do initialization stuff here
>     }
> }
>
>
> -Mike
> [1] https://externals.io/message/123675#123684
> [2] https://stackoverflow.com/a/2400206/102699
>

Seeing an extra keyword made me think of:
```php
class Foo
{
    public constructor __construct() {}
    public destructor __destruct() {}
    public static constructor __construct() {}
    public static destructor __destruct() {} // probably doesn't make sense
right now
}
```
This syntax would allow named constructors in the future, or even omitting
the default name.
```php
class Foo
{
    public constructor() {}
    public destructor() {}

    public constructor create(int $id)
    {
        $this->id = $id; // no need to call the default __construct, nor
needs to return
    }
}
```
Not sure if this is even a desired path to take, just wanted to throw the
idea out there.


Thread (16 messages)

« previous php.internals (#123692) next »