Re: Class static initialization block
| From: | Mike Schinkel | Date: | Mon, 13 Sep 2021 17:42:09 +0000 |
| Subject: | Re: Class static initialization block | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-116040@lists.php.net to get a copy of this message | ||
> On Sep 13, 2021, at 12:26 PM, Rowan Tommins <rowan.collins@gmail.com> wrote:
>
>> 2.) Make the initialization function private.
>
> I'm not sure how that would work: a private constructor means that it has to be explicitly
> called from within the same class, but a static initialiser would be called by the engine, before
> the class scope even existed.
I think we are getting in the weeds here and loosing sight of the desired outcome.
Currently it is not possible for a developer to disallow calling a class initialization method from
outside of the class. However that would end up being achieved — via private methods, protected
methods, or even voodoo — those details are unimportant to ultimately disallowing the calling of
initialization code from outside the class.
> From your link, it seems that C# restricts them much more than methods or constructors:
>>
>> A static constructor doesn't take access modifiers or have parameters.
>> A class or struct can only have one static constructor.
>> Static constructors cannot be inherited or overloaded.
>> A static constructor cannot be called directly and is only meant
>> to be called by the common language runtime (CLR). It is invoked
>> automatically.
Those all sound like they would be appropriate restrictions for PHP too.
> Apparently, the JS implementation does allow multiple static initialiser blocks in one class,
> which are simply processed in order. But JS classes are weird creations, implemented as a complex
> sugar on top of a classless object system, so may not be the best point of reference for PHP, whose
> object system much more closely resembles Java or C#.
I did not reference JS — I only referenced Java and C# — so JS' approach was not part of my
argument.
-Mike