Re: Access property of object stored in a constant

From: Date: Sat, 19 Aug 2023 08:48:06 +0000
Subject: Re: Access property of object stored in a constant
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-120919@lists.php.net to get a copy of this message
Hi Juliette > > Since https://wiki.php.net/rfc/new_in_initializers we can > > store > > objects in global constants. However, we may not actually read or > > write to the properties of those objects without first fetching the > > constant into a local variable. > > > > const a = new stdClass; > > a->b = 42; // Fatal error: Cannot use temporary expression in write context > > $a = a; > > $a->b = 42; // Works fine > > > > This issue was reported twice, so it seems like this code is generally > > expected to work. > > https://github.com/php/php-src/issues/10497 > > https://github.com/php/php-src/issues/11781 > > > > I have created a patch here to add support for this syntax: > > https://github.com/php/php-src/pull/11788 > > I totally understand that people are trying to do this, but this still > very much feels like scope creep. > > IIRC the new in initializers feature was _intended_ only for enums > (which can't take properties). Now suddenly a "constant" would no longer > be constant... In which case, what's the point of declaring it as a > constant ? This patch doesn't change the mutability of objects in constants, as they already don't offer interior immutability. https://3v4l.org/s7rHE This is analogous to const in JavaScript or readonly properties in PHP, where we can't change the value of the variable (or const in this case), but we can modify the properties of the object it's pointing to. I believe the main motivation for new in constant expressions was to support nested attributes. Enums have their own mechanism for instantiating cases. Since it was decided to expand the support for new to global constants, I would expect it to work with other language constructs, unless there's a good reason for it not to. Ilija

« previous php.internals (#120919) next »