Require backslash prefix for global functions and constants

Created on 20 January 2022, about 3 years ago
Updated 12 March 2024, about 1 year ago

Problem/Motivation

This is something that I first learned thanks to the EA Extended / EA Ultimate plugin for PhpStorm.
When calling/referencing global-namespace functions or constants from within a namespace, there is some ambiguity:

namespace N;

use function strpos as strpos_alias;
use const T_STRING as T_STRING_ALIAS;

strpos(..);  // Calls \N\foo() if exists, or \foo() otherwise.
\strpos(..);  // Calls \foo();
strpos_alias(..);  // Calls \foo();

print T_STRING;  // Prints constant \N\T_STRING if exists, or \T_STRING otherwise.
print \T_STRING;  // Prints constant \T_STRING.
print T_STRING_ALIAS;  // Prints constant \T_STRING.

The non-qualified reference does have a minor performance impact, which can become relevant for repeated low-level operations.
See https://github.com/Roave/FunctionFQNReplacer for benchmarks and further reading.

In Drupal, I mostly see function calls without the clarifying leading backslash.
Outside of Drupal, I see a mix of "use function" and FQN (leading backslash) for functions, and mostly imports for constants.

I don't see a recommendation about this in our coding standards.
See https://www.drupal.org/docs/develop/standards/coding-standards#functcall β†’

I personally like backslash for functions and constants when writing new code - this way I don't have to keep the imports up to date, and I can easily distinguish top-namespace functions from imported namespaced functions. Plus I don't need to create aliases for namespaced constants or functions used in the same file.
For existing code, it might be less disruptive to add the imports. Although I think the auto merge resolution in PhpStorm handles the added backslash more smoothly than added imports.

Proposed resolution

Decide whether we should
- recommend or prescribe backslash.
- recommend or prescribe imports.
- recommend or prescribe to use the ambiguous reference without backslash or import.
- leave it up to the developer.

Then decide whether this should be updated in core, or just be applied to new code.

Remaining tasks

User interface changes

API changes

Data model changes

πŸ“Œ Task
Status

Active

Component

Coding Standards

Created by

πŸ‡©πŸ‡ͺGermany donquixote

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024