On 11-05-2021 11:56, Nikita Popov wrote:
> 
> An issue for using new in (non-static) properties is that these objects are
> going to get created even if the constructor doesn't run. This could be a
> problem for things like unserialize() and anything that implements related
> functionality in userland (e.g. Symfony's VarCloner). In particular, this
> means that the default is *always* going to be constructed and populated,
> even if you're bypassing the constructor. Of course, this also happens with
> other property defaults, but in this case object construction may be more
> expensive (and possibly side-effecting). That's not great, and there
> wouldn't really be any way to avoid that.

That sounds like a bad situation to me.

> The alternative would be to instead only initialize such properties in the
> constructor, which comes with its own caveats: We'd have to make all
> classes actually have a constructor, and you'd have to make sure to call
> parent::__construct() even if there is no explicit parent constructor,
> otherwise you might be missing some property initializations. This also
> causes something of an asymmetry between "simple" default values
> (initialized on object creation) and "complex" defaults (initialized during
> constructor call).

The requirement of having to call the parent constructor would start
making sense in case we had a built-in base class that represents all of
the features that any PHP class has by default, including a constructor.
This class could act like an explicit base class that you can extend in
order to inherit the property initialization feature.

The idea is similar to the so called new style classes in Python where
you extend "object". This base class basically contains default
implementations of magic methods like __init__().

So the use of "new" in initializers would require extending this base
class and call the parent constructor. Maybe forgetting to do so could
throw, preventing initializers from silently not working.


Regards,
Dik Takken

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

Reply via email to