PHP

An Introduction to PHP Namespacing
14.01.2022
img

Why namespaces

When your project grows in complexity, you’ll need to integrate the code from others. Sooner or later, you’ll find that your code has different classes with the same name. This problem is known as name collision.To resolve it, you can use namespaces.

Namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  • Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  • Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
What is a namespace
It’s easier to understand namespaces by analogy to the directory structure in a filesystem.
A directory stores related files, which is similar to a namespace that groups related classes.
A directory doesn’t allow you to have two files with the same name.
However, you can have files with the same names in different directories. Likewise, namespaces mimic the same principle.By definition, namespaces provide you with a way to group related classes and help you avoid any potential name collisions.
Namespaces are not limited to group classes. They can group other identifiers, including functions, constants, variables, etc.

back to all posts