⊗ppOpNsRPt 100 of 107 menu

Relative Paths in Namespaces in OOP in PHP

Let the following call occur in the file index.php:

<?php namespace Admin\Data; new \Core\Controller; ?>

As you already know, when accessing a class, a backslash should be written before its namespace. In fact, this is not necessary. If this slash is not written, then the called namespace will be calculated relative to the current namespace. See the example:

<?php namespace Admin\Data; new Core\Controller; // equivalent to \Admin\Data\Core\Controller ?>

Given two classes:

<?php namespace Modules\Shop\Core; class Cart { } ?>
<?php namespace Modules\Shop; class UserCart extends \Modules\Shop\Core\Cart { } ?>

Simplify the code for class inheritance, considering that the namespaces of our classes have an overlapping part.

Given two classes:

<?php namespace Core\Data; class Controller { } ?>
<?php namespace Core\Data; class Model { } ?>

This is how objects of these classes are created in the file index.php:

<?php namespace Core\Data; $controller = new \Core\Data\Controller; $model = new \Core\Data\Model; ?>

Simplify the code for creating objects, considering the namespace in which objects of our classes are created.

byenru