Re: [DISCUSSION] Checking uninitialized class properties

From: Date: Fri, 17 May 2024 21:47:41 +0000
Subject: Re: [DISCUSSION] Checking uninitialized class properties
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-123339@lists.php.net to get a copy of this message
On Fri, May 17, 2024, at 9:40 PM, Luigi Cardamone 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. This is a gap in the current API, and I've run into it myself. What I figured out was: array_key_exists($prop, get_object_vars($obj)) Because get_object_vars() omits uninitialized values. I would absolutely like a better alternative. --Larry Garfield

« previous php.internals (#123339) next »