On 27/05/2021 16:33, Mike Schinkel wrote:
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?


Yes, that is my view. The problem is that there is currently no easy way to enforce this, because constructors are just methods that run after the object is created, and there are a handful of ways to create objects without calling them at all which would need to be accounted for as well.


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.?


Implicitly assigning a default from some magic list would be messy, but requiring that the user specified one would be trivial (or would have been, when typed properties were added): ?Foo $foo=null; int $bar=0; etc

The problem is that for non-scalar, non-nullable properties, there is no way to specify a default. One solution would have been to simply ban such declarations (i.e. require ?Foo $foo=null rather than Foo $foo) but that was considered too restrictive, so marking the properties "uninitialized" is the compromise.

We're probably stuck with that compromise for now, but continuing to treat it primarily as an error state hopefully leaves us room to do something cleaner in future if we can work out how.


Regards,

--
Rowan Tommins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to