[DISCUSSION] Checking uninitialized class properties

From: Date: Fri, 17 May 2024 21:40:19 +0000
Subject: [DISCUSSION] Checking uninitialized class properties
Groups: php.internals 
Request: Send a blank email to internals+get-123338@lists.php.net to get a copy of this message
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

« previous php.internals (#123338) next »