PHP Namespaces

The PHP namespace is essentially a container that you can keep all of your classes and functions in as a way of preventing name collisions with other classes and methods that have the same name as those in your namespace. Large applications often have hundreds or thousands of components, which lead to a large number of name-clashes. Namespaces allow you to elegantly group components and avoid this problem all the while allowing you to maintain simplicity in your naming conventions instead of having to keep up with complex naming conventions.

You can think of a namespace as being kind of like a directory on a file system. Say you’re running Windows and you have the following two directories on your C: drive, C://DIR_A and C://DIR_B. Now say you have two different text files with the same name, test.txt. Both of these text files can’t exist in the same directory but they can co-exist if you put one in C://DIR_A/test.txt and the other in C://DIR_B/test.txt. Namespaces work in a similar way in that you can have multiple functions, classes and methods with the same names all in the same application or file if they are located in different namespaces.

A namespace is defined with the namespace keyword and a name. It must be declared before any other code, with the exception of rarely used declare statements. Once defined, the scope of the namespace applies to the entire file.


Multiple namespaces may be defined in a single file by using the namespace keyword multiple times. In such instances, the scope of the preceding namespace ends once the next namespace definition appears.

Multiple Namespaces


Comments are closed.