Thank you for your feedback. I am already using a solution like the one proposed by Robert: it works but it leaves some doubts since each project can have a different name for NotSet while it seems a general concept of the language.
Besides the example I proposed, I think that there are many cases where you can check if the property is initialised or not and for consistency "null" should be considered a valid initialization value. Are there any downsides in adding a specific syntax to check if a property is initialized with any value? Thank you. Luigi Cardamone Backend developer Italy Il Sab 18 Mag 2024, 11:19 Robert Landers <landers.rob...@gmail.com> ha scritto: > On Fri, May 17, 2024 at 11:43 PM Luigi Cardamone > <cardamonelu...@gmail.com> wrote: > > > > Hello Internals, > > during last PHPDay in Verona I discussed this topic with some of > > you and it was suggested to me to send an email here. > > > > Here is an example to describe my problem. Imagine a simple > > DTO like this: > > > > class MyDTO{ > > public ?int $propA; > > public ?int $propB; > > } > > > > Imagine that a Form processor or a generic mapper fill some of > > these fields with a null value: > > > > $dto = new MyDTO(); > > $dto->propA = null; > > > > Sometimes we use DTOs to handle PATCH requests and not all > > the properties are mapped with a value. In a scenario like this, > > "null" is often a valid value. > > > > At this point, I need a way to find if a property was initialized or > > not but unfortunately "isset" is not a solution. When I write: > > > > echo isset($dto->propA) ? 'init' : 'not-init'; > > > > I get "not-init" since isset returns true only if the variable is set > > and different from null. > > > > Full example: https://3v4l.org/4cCj0 > > > > Is the language missing a clean way to check if a property is > > initialized or not? Is there any solution to this problem? > > > > The only alternative is using reflection but I need to pass the > > property name as a string losing static analysis. > > Proposing a new language syntax like > > "is_initialized($dto->propA)" can be an interesting solution? > > > > Thank you in advance. > > > > Luigi Cardamone > > Backend developer > > Italy > > I wouldn't rely on checking initialized or not. Instead, use a sentinel > value: > > class NotSet {} > > define("NotSet", new NotSet()); > > class MyAwesomeValue { > public NotSet|null|string $aValue = NotSet; > } > > This way, even programmers can "unset" a property by simply setting > $value->aValue = NotSet without having to rely on the weird PHP > semantics of unsetting a property. You can also use this to > declaratively encode which properties cannot be unset, without having > to define it in your mapping code. > > Robert Landers > Software Engineer > Utrecht NL >