A PHP namespace declaration is a language construct used to encapsulate classes, interfaces, traits, enums, functions, and constants into distinct, hierarchical logical scopes. By defining a namespace, you alter the current execution context, requiring the PHP engine to resolve identifiers relative to that declared scope rather than the global space. The declaration is executed using theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
namespace keyword.
Core Rules of Declaration
- Positioning: A namespace declaration must be the very first statement in the PHP script. The only PHP construct permitted to precede a
namespacedeclaration is adeclarestatement (e.g.,declare(strict_types=1);). Whitespace and comments are permitted inside the<?phptag before the keyword, but any non-PHP code, HTML, or whitespace output before the opening<?phptag will result in a fatal parser error. - Naming Conventions: Namespace identifiers must follow standard PHP naming rules (starting with a letter or underscore, followed by any number of letters, numbers, or underscores).
Standard Declaration
A standard namespace is declared using thenamespace keyword followed by the identifier and a terminating semicolon.
Sub-Namespace Declaration
PHP supports hierarchical namespace architectures. Sub-namespaces are declared by separating identifiers with the backslash character (\).
Multiple Namespaces in a Single File
While generally discouraged by PSR-4 autoloading standards, PHP permits declaring multiple namespaces within a single file. This can be achieved using either unbracketed or bracketed syntax. Bracketed Syntax (Recommended for multiple namespaces): When using bracketed syntax, all code belonging to the namespace must be enclosed within the curly braces. No code may exist outside of these brackets, with the explicit exception of a validdeclare statement.
namespace declaration is encountered.
Global Namespace Declaration
If a file containing multiple namespaces requires code to be executed in the global scope, it must be declared using the bracketed syntax without an identifier. Mixing bracketed and unbracketed syntax in the same file is invalid and will throw a fatal error.Master PHP with Deep Grasping Methodology!Learn More





