DEV Community


Posted on • Updated on

Demystifying Namespaces and Organizing Your Code in PHP

In PHP, namespaces allow classes/functions/constants of the same name to be used in different contexts without any conflict, thereby encapsulating these items. A namespace is a logical grouping of classes/functions etc depending on their relevance. Just as a file with the same name can exist in two different folders, a class of a certain name can be defined in two namespaces. Further, as we specify the complete path of a file to gain access, we need to specify the class’s full name along with the namespace.

screenshot showing how to define name spaces in PHP
To call a function defined inside a namespace, include with use keyword. Name of function is qualified with namespace
When to Use Namespaces?
The use of namespaces becomes crucial when application code grows. To give a unique name to each class/function may become tedious and not exactly elegant, a namespace comes in handy. For example, if we need to declare a calculate() function to calculate the area as well as tax, instead of defining them as something like calculate area() and calculate tax(), we can create two namespaces area and tax and use calculate() inside them.
The use of namespaces solves two problems.
• Avoid name collisions between classes/functions/constants defined by someone with third-party classes/functions/constants.
• provides the ability to alias (or shorten) Extra_Long_Names thereby improving the readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces, functions, and constants. Namespace names are case-insensitive.

screenshot showing ow to Use namespaces

In the above illustration, we import the SomeClass from the SomeNamespace using the use keyword. This allows us to use the class directly without specifying the fully qualified name each time.

Top comments (0)