Introduction to Namespaces in OOP in PHP
If, when running a PHP script, there are two classes with the same names, they will conflict, which will lead to a fatal error. This is actually not very convenient, as you constantly have to monitor the uniqueness of names.
For example, consider the following situation:
you have a site with users
and an admin. At the same time, in the users folder, the
classes for users are stored, and in the admin folder
- classes for the admin.
Suppose both users and the admin need a certain
class Page responsible for some
pages of the site. At the same time, there will be
one class for users, and another for the admin. In this
case, we are faced with a name conflict.
The simplest way to resolve this conflict
is to give the classes different names, for example,
UsersPage and AdminPage. This
path, however, gradually leads to the appearance of
very long class names.
In PHP, there is another way to solve the problem - namespaces. The essence is as follows: each class can belong to some namespace, and the uniqueness of class names only needs to be maintained within this namespace.
That is, to solve our problem, we can
do the following: assign one class Page
to some namespace, for example,
Users, and the second class Page
to another namespace, for example,
Admin.