In a broad sense, namespaces are a way of wrapping up items. Many computer programs and applications apply this concept to file handling.
Let’s take a look at an operating system. Directories and folders serve as wrappers for related items. Therefore, they must have names that are distinct from other directories in the same hierarchy. Although files in a particular folder cannot have the same name, different folders can contain files with the same name. They can even contain duplicate copies of the same file!
We can consider the folders to be acting as namespaces for the files. To reference a file in any folder—for example, man.txt
in the documents
folder—you indicate the relative name—documents/man.txt
—for such file. This is a simple explanation of what namespaces are in the programming sphere.
In the PHP programming language, namespaces are a special way to separate files with unique name identifiers. Authors of libraries and applications often face problems creating reusable code elements like classes and functions. Namespaces are designed to solve such problems. For example:
Namespaces prevent the collision of names between our codes and classes, functions or constants inbuilt in PHP or third-party classes. They also prevent this for the functions and constants we integrate into our code.
Namespaces solve the problem of extra-long names. Instead, they let us use aliases or shortened names. This improves the readability of our code.
namespace mynamespaceName;
Here, the mynamespaceName
can be any identifier we choose for our namespace. It can also be a directory path, such as my\name\space
.
We should keep the following in mind when we define namespaces:
Namespaces are case-insensitive. Namespaces like
PHP\Classes
are internal to PHP, and we should not use them in our user-defined spaces.Namespaces should be defined at the top of the script. This ensures that every function, class, or constant we use in such a script is automatically placed under the namespace.
Namespaces are declared using the
namespace
keyword.
The code snippet below is a simple example of the use of namespaces.
<?phpnamespace MyNamespace1{function pens(){echo "this is in first function";}}namespace MyNamespace2{function pens(){echo "this is in the second function";}}namespace Mynamespace3{function pens(){echo "this is in the third function";}}/* I created three different namespaces above// all of which contains functions all of the same name.*/?>
The code above will return without raising errors even with the same function name given to different function blocks. This happened because, each function is found in a separate namespace.
Also, if this snippet was a script and is included or required in another script, each function can be called and it will can execute separately with its own operations using their namespaces.