Press enter to see results or esc to cancel.

What is a namespace?

In this article you will learn what a namespace is in PHP, how to create one and how to use it.

So what is a namespace?

Here is an intuitive way to think about namespaces:

  • Imagine a filesystem on a computer. If functions and classes are files, then namespaces are directories. You can have tons of files with unique names inside a directory, but you cannot have two files with the exact same name in a directory.

What is the use of a namespace?

Namespaces are good for two things:

  • Organize code into logical groups.
  • Prevent naming collisions that may occur if you include libraries.

Organize code into logical groups

Let’s go back to the filesystem example again. If you are a somewhat tidy person, you probably use folders to organize your files on your computer. Games may go into a games folder, assignments may go into an assignments folder and so on. The same idea goes for namespaces.

Let’s imagine we want to create a library for image manipulation. We may want to share it with the world, or at least, re-use it in future projects. In order to make it easier for people or our future selves to use the library we use namespaces.

Why? Because now, whenever someone wants to use our library, they can simply import it and immediately start using it. This goes hand in hand with preventing naming collisions.

Preventing naming collisions

Okay, so organization is a good thing but what is a naming collision and why do they go hand in hand?

A naming collision is simply when two classes or two functions have the exact same name and the compiler cannot figure out which class or method you intended to use at that time. A namespace solves this because you are basically putting them into their own folders; the namespaces themselves becomes identifiers.

Example

Let us go back to the filesystem example. As previously stated, you cannot have two files with the same exact name in the same folder. You can have “file.txt” and “file(1).txt” in the same folder, but never two files called “file.txt”.

You can however have them on the same system, if you put one “file.txt” inside its own folder “/games” and another “file.txt” into its own folder “/work”… I think you get the idea. As long as the folder names are unique you can have as many folders containing its own version of “file.txt” as you want.

Not using namespaces is akin to putting every file on the desktop. It will become a problem once you have reusable code and want to use it for future projects. Having your own personal list of names you cannot use because you imported x or y code will quickly become unmanageable. It becomes even more of a problem if you share your code with other people because they may already have classes and methods with the same names. Common class and function names are especially risky:

  • Person
  • Image
  • Customer
  • Database
  • getName()
  • editCustomer()
  • deleteImage()
  • addPerson()

and so on.

Okay so how does naming collisions work?

Imagine this code:

// inside libraryA.php    
function getImage(){
   echo "This is image A";
 }
// inside libraryB.php    
function getImage(){
   echo "This is image B";
 }
// inside index.php
include_once('./libraryA.php');
include_once('./libraryB.php');

Now you have imported two getImage() functions that do two different things. You will get errors that complain about redeclaring functions, which by definition, you are. You are first asking to bring in getImage(). When that is done, you are asking to bring in (the other) getImage()… again.

In PHP you may get errors like:

  • Fatal error: Cannot declare class MyAwesomeLib, because the name is already in use in C:\Users\name\Desktop\myproject\classes\libraryB.php on line 2

or

  • Fatal error: Cannot redeclare myAwesomeFunc() (previously declared in C:\Users\name\Desktop\myproject\classes\libraryA.php:3) in C:\Users\name\Desktop\myproject\classes\libraryB.php:3 on line 4

The issue behind these errors can be name collisions.

Using namespaces and functions

To prevent name collisions, we organize the code into different “folders”.

// Define a namespace
namespace Whatever\You\Want;

// a few examples
namespace CodestationIO;
namespace CodeStationIO\Image\Tools;
namespace Tools\Images;

// code goes here...
// inside libraryA.php    
namespace MyLibrary\A;

function test(){
   echo "This is library A";
 }
// inside libraryB.php    
namespace MyLibrary\B;

function test(){
   echo "This is library B";
 }

Using a function inside a namespace

There are two ways to use a function that is inside a namespace.

Either including the full namespace:

// inside index.php
include_once('./libraryA.php');
include_once('./libraryB.php');

// run test methods
MyLibraries\A\test();
MyLibraries\B\test();

Or use the Use statement. You can use the use statement in two ways:

// by including the "as" keyword, you can refer to the namespace by this variable.
use full\namespace\path as foo; 

// examples
use MyLibraries\A as A;
use MyLibraries\B as foo;

// run methods
A\test();
foo\test();
// by omitting the "as" keyword, you can refer to classes as 

// examples
use MyLibraries\A as A;
use MyLibraries\B as foo;

// run methods
A\test();
foo\test();
// inside index.php
include_once('./classA.php');
include_once('./classB.php');

// use statement for and what you want to refer it as in the code.
use MyLibraries\A as A;
use MyLibraries\B as B;

// run test methods
A\test();
B\test();

Namespaces and classes

Classes are a bit different. You actually include the class name in the use statement. After that, you can refer to the class by whatever identifier you choose.

For example, imagine you have a class called “ClassA” inside the namespace “MyClasses”.

use MyClasses\ClassA as myClass;

// now you can refer to it as "myClass" in your code.
$foo = new myClass();
$foo->anAwesomeMethod();

// if you omit the identifier, then the class will be referred to its 
// original class name by default
use MyClasses\ClassA;

$foo = new ClassA();
$foo->anAwesomeMethod();

Conclusion

Now we have learned that a namespace is like a folder or directory in a filesystem. It helps organize files and allows multiple files in the project to have the same name. In programming, namespaces allow functions and classes to have the same names without creating a name collision. 99.99999% of all libraries you will ever use will have their own namespace you can refer to in order to pull out the classes and functions you need, even if those same names already exist in your own project.

When you have defined a namespace you can use it by including the full namespace path you want to access or by using the use-statement. The use-statement allows you to attach an identifier to an otherwise long namespace for better readability. This new identifier can then be used to refer to the namespace in your code.

For classes you want to include the class name in the namespace. If you skip the identifier, then any class will be identified by its original class name.

More reading