When a PHP file uses bracketed namespace syntax, every executable statement must also be inside a namespace block. Put global bootstrap code inside an empty namespace { ... } block.
Last updated: October 18, 2026.
<?php
declare(strict_types=1);
namespace Tools {
final class Formatter
{
public static function label(): string
{
return 'Ready';
}
}
}
namespace {
echo Tools\Formatter::label();
}The named block declares the class. The empty namespace block returns to global code without placing PHP statements outside the braces. This structure is valid when legacy bootstrap code cannot yet be moved into a separate entry file.
Do not mix the two namespace syntaxes
The PHP manual describes simple and bracketed syntax for multiple namespaces. A file may use one style or the other, but should not mix them. With bracketed syntax, no PHP code may sit outside the blocks except an opening declare statement.
The empty namespace {} block is the supported way to combine global code with namespaced declarations. Output, function calls, object creation, and includes count as code. Comments and whitespace are not the cause of “No code may exist outside of namespace {}”; an executable statement in the wrong position is.
Prefer one namespace per application file
Although PHP permits multiple namespace blocks, application classes are usually clearer when each file declares one namespace and contains no bootstrap work. Composer autoloading then maps classes to files, while an entry script loads the autoloader and starts the application in global space.
A namespace declaration must appear at the top of its file, after an optional declare. The PHP namespace definition rules also prohibit HTML or other output before the declaration. Prefix a global class or function with a leading backslash only when name resolution could otherwise select a namespaced symbol.
Run php -l file.php after restructuring the file. Continue with PHP functions, parameters, and scope, maintainable PHP application structure, and Symfony namespace-based service loading.