Hello internals,

After seeing some discussions about using enum values as keys, I
thought of my own implementation of `nameof` (from C#) that is very
hackish: https://github.com/withinboredom/nameof

I'd like to propose making it a real thing (with better behavior than
my hack). An operator like this has a few niche uses, mostly for
better error messages but also for making strings of things that you
normally can't get the string value of. Here are some examples:

nameof(func(...)) === 'func'
nameof($party) === 'party'
nameof($captain->planet) === 'planet'
nameof(Class::Prop) === 'Prop'

I first attempted this as an extension, but this belongs at the
parsing/compiling level and not during runtime (this gets turned into
a constant zval).

I use my (very hacky) implementation to handle stringifying enums
(mostly), as well as better, easier-to-refactor error messages:

throw new InvalidArgumentException(nameof($var) . ' has an unexpected value');

Without it, the name of the variable can be missed in a refactor,
making the error message useless or incorrect.

The code to make this possible (without much error checking) is
relatively simple: https://github.com/php/php-src/pull/11172

Robert Landers
Software Engineer
Utrecht NL

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to