Namespace Subspaces in OOP in PHP
Now let's consider a more complex situation:
for the admin, we need to create two classes Page
- one with page data, and the other - with the presentation
of this data. Let the first class be located
in the file /admin/data/page.php, and the second
- in the file /admin/view/page.php.
In previous lessons, we already decided that all classes from the folder
admin will belong to the namespace
Admin. However, now within this
very namespace, we have a conflict between two classes.
To solve the problem, we can create additional
namespace subspaces. For example, we can have the
namespace Admin, and within it, the subspaces
Data and View. In this case,
the names of these subspaces are simply written
using a backslash - both when defining the namespace
and when creating an object of the class.
It should be clarified here that the nesting level of subspaces is not limited (you can create sub-subspaces within subspaces and so on).
So, let's complete our example described above.
For the Page class from the file /admin/data/page.php,
we will specify the namespace Admin\Data:
<?php
namespace Admin\Data;
class Page
{
}
?>
For the Page class from the file /admin/view/page.php,
we will specify the namespace Admin\View:
<?php
namespace Admin\View;
class Page
{
}
?>
Let's create objects of our classes:
<?php
require_once '/admin/data/page.php';
require_once '/admin/view/page.php';
$adminDataPage = new \Admin\Data\Page;
$adminViewPage = new \Admin\View\Page;
?>
Suppose you have a folder modules/cart.
Make it so that all classes from this folder
belong to the namespace
Modules\Cart.
Suppose you have a folder modules/shop/cart/.
Make it so that all classes from this folder
belong to the namespace
Modules\Shop\Cart.