By default, all constant, class, and function names are placed in the global space ? like they were before PHP supported namespaces.
Namespaced code is defined using a single namespace keyword at the top of your PHP file. It must be the first command (with the exception of declare) and no non-PHP code, HTML, or white-space can precede the command, e.g.
1 2 3 4 |
&lt;?php<br /> // define this code in the 'MyProject' namespace<br /> namespace MyProject;<br /> // ... code ...&lt;/p&gt;<br /> |
The code following this line will be assigned to the ?MyProject? namespace. It is not possible to nest namespaces or define more than one namespace for the same code block (only the last will be recognized). However, you can define different namespaced code in the same file, e.g.
1 2 3 4 5 6 7 8 9 10 11 |
<br /> &lt;?php<br /> namespace MyProject1;<br /> // PHP code for the MyProject1 namespace<br /> namespace MyProject2;<br /> // PHP code for the MyProject2 namespace<br /> // Alternative syntax<br /> namespace MyProject3 {<br /> // PHP code for the MyProject3 namespace<br /> }<br /> ?&gt;<br /> |
Although this is possible, I would advise against it: retain your sanity by defining a single namespace per file.
Sub-namespaces
PHP allows you to define a hierarchy of namespaces so libraries can be sub-divided. Sub-namespaces are separated using a backslash () character, e.g.
. MyProjectSubName
. MyProjectDatabaseMySQL
. CompanyNameMyProjectLibraryCommonWidget1