Re: Consensus Gathering: is_initialized
| From: | Mike Schinkel | Date: | Thu, 27 May 2021 15:33:09 +0000 |
| Subject: | Re: Consensus Gathering: is_initialized | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-114645@lists.php.net to get a copy of this message | ||
> On May 27, 2021, at 10:43 AM, Rowan Tommins <rowan.collins@gmail.com> wrote:
>
> On 27/05/2021 14:55, Andreas Leathley wrote:
>>
>> When using isset on a non-nullable property a
>> static analyzer would rightfully complain that the property is not
>> nullable
>
>
> Precisely, so don't mark a property as non-nullable and then leave it unset.
>
>
>> isset in this case is abused to check for uninitialized, hiding the
>> actual intent
>
>
> On the contrary, the uninitialized state is what is being abused. If you want to make the
> intent clear, use a clear flag of "needs lazy-loading", or whatever you're actually
> using this magic "not null but not really anything else either" state for.
If in fact that uninitialized state is "being abused" as asserted, maybe the real abuse is
the fact that PHP allows such a state to exist in the first place?
Since the argument against is_initialized() seems to almost universally be that we should not write
code that lets type properties be uninitialized past the constructor then it would follow that PHP
is in the wrong to even allow uninitialized state past the constructor?
If a property is defined as
?int or null|int why should PHP allow an
uninitialized state to begin with? Why shouldn't PHP initialize any of those properties to
null to begin with?
And for non-nullable, why shouldn't PHP default int to 0, string to
"", array to [], etc.?
But if the answer is that PHP *should* have an uninitialized state past the constructor then it
makes good sense to have a *performant* is_initialized() function to allow userland to discern the
difference when applicable use-cases occur.
Maybe the proper solution would be for PHP to set a default value to any uninitialized properties at
the end of the constructor, null for properties that are nullable or objects, and a known default
for any scalar types? Then post-constructor it would not be possible to have uninitialized and thus
no need for the function?
-Mike