Defining objects as constants

php.internals

Dominic Grostate

4 years ago
This actually works in PHP8, is it intentional? class Item { } define('ITEM', new Item()); class Sample { public const ITEM = ITEM; } var_dump(Sample::ITEM); // object(Test\Item)#3 (0) { // }

Rowan Collins

4 years ago
On Fri, 19 Aug 2022 at 12:05, Dominic Grostate <codekestrel@googlemail.com> wrote:
> This actually works in PHP8, is it intentional? > > class Item > { > > } > > define('ITEM', new Item()); >
More specifically, this works since PHP 8.1, as shown by this handy tool: https://3v4l.org/UTcfO I believe it came about as almost a side-effect of https://wiki.php.net/rfc/new_in_initializers although it also fits well with enums (which are special objects), since it allows you to do things like this: enum DayOfWeek { case MONDAY; case TUESDAY; case WEDNESDAY; case THURSDAY; case FRIDAY; case SATURDAY; case SUNDAY; } define('SCHEDULED_DAY', DayOfWeek::TUESDAY); Regards,
-- Rowan Tommins [IMSoP]