Functions and Constants in Namespaces
An unqualified call to strlen() inside a namespace can represent two entirely different functions in
PHP, and looking at a single isolated file, it is impossible to know which one is intended. Because of this, code style tools have
to guess on a whole range of common fixes. In most cases, a single line of configuration is all it takes to tell DressCode what
exists in your namespaces, and automated fixes immediately stop being risky. Certain names also open the way to faster function calls.
One Name, Two Meanings
Take a look at the following snippet:
namespace App;
if (is_null($user)) {
// ...
}
Which function is actually being called here? Most developers naturally assume it's the global is_null() that
everyone knows. But PHP resolves this only at runtime: first it checks whether a local App\is_null() function exists,
and only if it doesn't does it fall back to the global one. All it takes is another file anywhere in your project declaring:
namespace App;
function is_null(mixed $value): bool
{
return $value === null || $value === '';
}
and the call above suddenly does something completely different. The file containing the call doesn't matter in the slightest: the only thing that decides behavior is whether that second file has been loaded.
Constants behave in the exact same way: PHP_EOL inside the namespace App resolves to
App\PHP_EOL if defined, and to the global PHP_EOL otherwise. Classes do not work this way: an
unqualified Exception inside App always unequivocally means App\Exception, and the global
class must be written as \Exception or imported via use.
Why does PHP treat functions differently from classes? When namespaces arrived in PHP 5.3, classes and functions got different
answers. For classes, a fallback to the global name combined with autoloading would have been a performance disaster: every
new Exception would first try to load a file for App\Exception. Functions and constants have no
autoloading, so they were granted a silent fallback to the global namespace, and code written before namespaces could move into
one without a backslash before every strlen(). It was a pragmatic compromise for its era; its cost is that the
meaning of an unqualified function call is not a property of the file but of the entire running program.
Why Tools Struggle with It
Code style tools inspect individual files in isolation, not a running process. Faced with is_null($x) inside a
namespace, a tool encounters the exact same ambiguity you faced above, and it cannot know the answer with certainty. Yet a whole
range of useful fixes assume the call is definitely the built-in PHP function:
- rewriting
is_null($x)to$x === null, intval($x)to a typecast(int) $x,sizeof($a)tocount($a),dirname(__FILE__)to__DIR__,get_class()toself::class,- adding
use function count;so the compiler can optimize the call.
If the function happened to be your own App\is_null(), every one of those edits would silently alter program
behavior. A responsible tool must therefore classify such transformations as risky fixes and refuse to make them without explicit
permission. PHP CS Fixer flags rules like is_null, no_alias_functions, and dir_constant as
risky for this exact reason: they are unsafe if the function is overridden locally.
And this is far from a theoretical concern. A well-known testing pattern relies entirely on this mechanism: libraries like
php-mock declare App\time() or App\file_get_contents() inside a test suite so that code under test in
the App namespace invokes a mock rather than the real runtime function.
Let's Be Pragmatic
How many custom functions and constants do you actually declare in your namespaces? In almost all codebases, the answer is very
few, and often none at all. Functions in PHP cannot be autoloaded: for a function to be callable, its file must be
explicitly loaded ahead of time via require or a files entry in composer.json. That is why
application logic moved permanently into classes long ago, leaving namespaced functions a rare edge case. Function autoloading has
been proposed for PHP multiple times, but has never become part of the language.
This is also an excellent reason never to rely on unqualified calls for namespaced functions: if the file containing the
function happens not to be loaded, PHP raises no error: it silently calls the global function of the same name, if one exists. An
explicit import use function App\is_null; won't autoload the file either, but it guarantees that the call fails
immediately and clearly with Call to undefined function App\is_null().
The reality is clear: the theoretical ambiguity affects everyone, but real custom functions in namespaces are exceedingly rare. All you need to do is enumerate them.
Tell DressCode What Is What
In the most common case, you declare no custom functions or constants in namespaces at all. When that is the case, a single configuration line is all you need:
nameResolution: certain
This single setting tells DressCode that every unqualified function or constant name that a file neither imports nor declares locally is guaranteed to be global. Not “probably,” but with absolute certainty.
If you do declare some custom functions or constants in namespaces, list them under the namespaces key: functions
under functions and constants under constants. Syntax matches standard use statements,
including groups in braces. Wrap grouped entries in quotes so NEON doesn't parse them as maps:
nameResolution: certain
namespaces:
functions:
- 'App\Utils\{format, parse}'
- App\Legacy\helper
constants:
- 'App\{VERSION, DEBUG}'
DressCode then treats any function in that list as belonging to its namespace wherever it is invoked without an import. For functions, letter case does not matter at all; for constants, case matters only in the constant's own name (not in the namespace path), matching PHP's native behavior.
The lists and nameResolution represent two separate concepts, which is why each has its own key. The list is a
statement of fact: this function exists. nameResolution is a decision: nothing else exists there.
nameResolution |
what it means |
|---|---|
certain |
The lists are complete; anything not listed is guaranteed to be global. |
uncertain |
The lists may be incomplete; identical to omitting the key. |
Under uncertain, DressCode acts with extreme caution: it assumes an unqualified name is global, but treats any
automated fix relying on that assumption as risky. It reports
the fix as a warning with an explanation on the line below the violation (e.g.
the namespace may declare `is_null()`), making the fix only when you list the decision in fixRisky or
pass --fix-risky. That is why uncertain is the default: placing a decision in your configuration does
not imply blanket consent to alter code behavior. The moment you configure certain, however, these fixes stop
being risky.
Every Rule Benefits
What matters most is where this knowledge is applied. DressCode doesn't pass this setting to individual rules in
isolation; it provides it to the shared NameResolver analysis, which resolves names across the entire tool. Built-in
rules query it, and so can your custom rules. The domain
knowledge lives in one central place, so no rule has to maintain its own list of exceptions.
This works just as reliably in reverse, when a rule writes a function name into code itself. The decision
hygiene.aliasFunctions replaces sizeof() with count() and writes the new name matching the
original formatting: \sizeof() becomes \count(), and bare sizeof() becomes bare
count(). However, if the file imports or declares its own count, or if the configuration declares
count() in that namespace, it emits \count(), ensuring the rewritten code calls the exact same function
as before.
All rules read every name with identical consistency, regardless of which rule queries it.
A New Function Does Not Slip Through
A static list would be a liability if it went stale. That is why DressCode guards the list itself: the moment your
configuration specifies nameResolution: certain, an internal validation check activates under
namespaces.functions and namespaces.constants. If DressCode encounters a newly declared function in a
namespace that is missing from the list, it flags it immediately (doing the same for const and
define('App\X', ...) calls). It even accounts for declarations inside conditions, such as a polyfill wrapped in
if (!function_exists(...)). The moment anyone adds a function like App\Utils\slugify(), running
dresscode check prompts them to update the configuration:
src/Utils/helpers.php error 12:10 Function `App\Utils\slugify()` must be listed in `namespaces.functions`. namespaces.functions
This check is enough because, unlike calls, declarations can be identified statically: they exist directly in the files
DressCode inspects. Just be mindful of excluded paths. If you declare a function in a test directory that DressCode skips, and the
code calls it without an import, add it to the list manually. Under uncertain, this check stays silent because there
is nothing to enforce. Under certain, not even --only can turn it off: fixes that rely on complete lists
cannot afford to lose the check that keeps them complete.
You don't need to assemble your initial list by hand either. Running dresscode init scans all files in your project paths,
discovers all functions and constants declared in namespaces, and writes their lists alongside
nameResolution: certain. If any file fails to parse (making its declarations unknown), init avoids
writing certain and names the unverified file in a comment. It writes the names of one namespace as a group, one
namespace per line ('Acme\Shop\{formatPrice, parsePrice}'), and a new name goes into any of the groups, or on its own
by its full name.
Helper Functions in Tests
Test suites frequently declare helper functions directly inside their test namespace, such as
App\Tests\createUser(). Adding these to your global configuration and maintaining them would be tedious noise. For
test directories, simply add a scoped override stating that lists are
incomplete there:
nameResolution: certain
overrides:
- paths: [tests]
nameResolution: uncertain
DressCode will then inspect files in tests cautiously: fixes requiring global functions will only be reported as
risky warnings, and the check for unlisted declarations remains silent. Production files in src continue to benefit
fully from the certainty. This separation works because production code never calls test helpers, meaning those functions have
zero influence on name resolution in src.
One exception deserves careful attention: the mocked function pattern discussed above. If a test declares App\time() to force production code in the
App namespace to invoke a mock, that change in behavior targets calls in src, not in the tests. Such a
function definitely belongs in the project's root namespaces.functions list so that rules in src leave
it alone.
Functions Declared by a Framework
Sometimes you write application code directly inside a framework's namespace because the framework's architecture was
designed for it. Symfony, for instance, directs service configurations into files beginning with
namespace Symfony\Component\DependencyInjection\Loader\Configurator;, specifically so that developers can invoke
helper functions like service(), param(), or env() without import statements. Those
functions are declared by Symfony itself inside vendor/, where DressCode does not look.
DressCode understands these framework helpers natively: whenever a project installs symfony/dependency-injection,
it automatically adds those functions to the internal namespaces.functions list without requiring a single line of
configuration, regardless of which coding standard you use. Running dresscode config lists them under the
Names line, attributed to DressCode for symfony/dependency-injection.
Other packages can supply their own namespace lists through the namespaces key in their data files, merging seamlessly with your configuration. However, neither a
package nor a preset can set the nameResolution key: they understand the framework, but they cannot speak for your
own application code.
How Global Names Are Written
How global functions and constants are written in code is controlled by the qualification section. Every name can be represented in
three ways, and each decision key accepts one of three values: bare leaves the name bare relying on runtime fallback,
imported requires an explicit use function or use const import, and
backslashed mandates a leading backslash.
qualification:
function:
global: bare
optimized: imported
constant:
global: bare
optimized: imported
Under this configuration, ordinary global functions and constants remain clean and bare, while those the compiler can optimize receive an import:
namespace App;
use function count;
use function in_array;
At first glance, this might look redundant: count() works perfectly without an import statement. But the sole
motivation is performance: with an import, the compiler has compile-time certainty that the function is global and applies its
direct opcode shortcut (as detailed in Faster Function Calls in
PHP).
Using optimized: imported can lengthen your file header with multiple use function
lines. You can keep headers compact using imports.grouping.function: combined,
which bundles functions into a single statement: use function count, in_array, strlen;. Fewer lines mean fewer
tokens: AI agents inspecting the top of a file reach meaningful business logic faster without having to parse through walls of
imports. The nette standard formats imports this way.
Keys in the section proceed from general to specific:
| key | which names it decides |
|---|---|
function.global, constant.global |
Standard global functions and constants in namespaces (excluding those governed by optimized keys). |
function.optimized |
Functions handled specially by the compiler, applied where a call with the given arguments is genuinely optimized. |
constant.optimized |
Constants the compiler evaluates downstream: inside conditions or constant expressions. |
function.currentNamespace, constant.currentNamespace |
Functions and constants belonging to the file's own namespace. |
For some functions, function.optimized depends on the arguments: PHP always optimizes strlen(), but
dirname(), defined(), and function_exists() are optimized only with constant arguments;
sprintf() is optimized only with a constant format string that contains nothing but %s and
%d specifiers, one for each passed value; and in_array() is optimized only with inline array literals.
A function falls under this key as soon as a namespace calls it in an optimizable way at least once, after which every reference
to that function in the namespace is formatted consistently. A function never invoked in an optimizable way falls back to
function.global, preventing unhelpful imports from cluttering the file. The constant.optimized decision
is similarly context-aware, looking at how the constant is used rather than its name. Setting bare on these keys
indicates that the project prioritizes clean, unadorned code over compiler shortcuts. Each name is governed by exactly one key: if
function.optimized is set to keep, optimized functions remain untouched, and
function.global: bare strips leading backslashes from \array_map() while leaving \strlen()
and \count() intact.
DressCode inserts imports matching the style your file already uses: integrating into existing multi-name statements, into
grouped imports for that namespace, and in correct alphabetical order so that decisions in the imports section have nothing to complain about. If the file
already imports the function under an alias, it reuses that alias. Where an import cannot be added (for instance, due to a naming
collision), it falls back to a leading backslash. Conversely, it strips backslashes only where a bare name safely reaches the
global function, and automatically removes orphaned imports that are no longer referenced.
This brings us full circle to namespaces. An import statement use function strlen; permanently binds calls to the
global function. If your project had its own App\strlen(), adding that import would break runtime behavior. Under
uncertain, DressCode therefore treats any transition between bare names and imports or backslashes as risky. Under
certain, it knows App\strlen() does not exist and applies the import safely. Naturally, it never imports
a function listed in namespaces.functions.
Classes do not suffer from this ambiguity: an unqualified class name in a namespace never falls back to the global namespace at
runtime. The keys class.otherNamespace and class.global therefore only choose between an import and a
backslash, and none of their automated fixes are risky. Identifiers without a leading backslash (such as Model\User
when use App\Model; is present) are left alone, as they resolve relative to imports or the file's namespace. In a
file without a namespace, leading backslashes are always redundant, and qualification.leadingBackslash cleanly
removes them.
Summary
- In PHP, an unqualified function or constant inside a namespace resolves either locally or globally, and an isolated file cannot tell which.
- Set
nameResolution: certainin your configuration (and list custom names undernamespacesif you have any). All rules will behave with complete certainty, and fixes relying on global names stop being risky. - Parts of the project where the lists are not complete, such as tests with helper functions, can use an override with
nameResolution: uncertain. - Without
certain, DressCode acts conservatively, applying such fixes only with explicit permission infixRiskyor via--fix-risky. - Newly declared functions in namespaces are automatically tracked and validated under
namespaces.functions;dresscode initgenerates your initial lists. - Always call namespaced functions using an explicit
use functionimport. If the file is not loaded, you will find out immediately via a clear fatal error. - Certain names let PHP make function calls much faster; see Faster Function Calls in PHP.