rfc:nameof

This is an old revision of the document!


PHP RFC: NameOf

Introduction

Currently, in PHP, it is possible to get the name of nearly anything. You can retrieve the name of a class with get_class or ::class, you can extract the name of a function from (...), but there is one thing you cannot get the name of, and that is the name of a variable or static member during run time.

Proposal

This RFC proposes introducing a new global function called nameof that returns the names of variables and static members. This string can assist in error messages, array keys for static/enums, or reflection. The name is extracted during compile time, and works anywhere a static string would work.

This function returns the 'name of' a variable, property, function, or static member.

Examples

nameof($variable) === 'variable';

nameof($object->property) === 'property';

nameof(Enum::Case) === 'Case';

nameof(Object::Member) === 'Member';

nameof(func(...)) === 'func';

nameof(some\func(...)) === 'some\func';

Backward Incompatible Changes

What breaks, and what is the justification for it?

Proposed PHP Version(s)

8.3: release 8.2.x: nameof becomes a reserved word, emitting a notice

RFC Impact

To SAPIs

Should be none

To Existing Extensions

Will existing extensions be affected? No

To Opcache

The function call is compiled to a string.

New Constants

None

Open Issues

None thus far

Unaffected PHP Functionality

PHP will largely be unaffected by this change, except that a new global function is introduced.

Future Scope

None.

Proposed Voting Choices

Include these so readers know where you are heading and can discuss the proposed voting options.

Patches and Tests

Implementation

After the project is implemented, this section should contain

  1. the version(s) it was merged into
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature
  4. a link to the language specification section (if any)

References

Links to external references, discussions or RFCs

Rejected Features

Keep this updated with features that were discussed on the mail lists.

rfc/nameof.1683497963.txt.gz · Last modified: 2023/05/07 22:19 by withinboredom