⊗ppOpNsCA 104 of 107 menu

Class Aliases for Namespaces in OOP in PHP

Suppose we have two classes Data, belonging to different namespaces. Suppose in some class we need objects of both these classes:

<?php namespace Project; class Test { public function __construct() { $data1 = new \Core\Users\Data; // create an object $data2 = new \Core\Admin\Data; // create an object } } ?>

Suppose we decided to simplify class calls via the use command. In this case, we face a problem: both classes have the name Data, which means we will have a name conflict:

<?php namespace Project; // There will be a name conflict: use \Core\Users\Data; // connect the first class use \Core\Admin\Data; // connect the second class class Test { public function __construct() { $data1 = new Data; $data2 = new Data; } } ?>

To solve this problem, there is a special command as that allows you to assign the connected class a pseudonym - a name under which this class will be available in this file. Let's rename our Data classes:

<?php namespace Project; use \Core\Users\Data as UsersData; use \Core\Admin\Data as AdminData; class Test { public function __construct() { $data1 = new UsersData; $data2 = new AdminData; } } ?>

Simplify the following code using use:

<?php namespace Project; class Test { public function __construct() { $pageController = new \Resource\Controller\Page; $pageModel = new \Resource\Model\Page; } } ?>

Simplify the following code using use:

<?php namespace Project\Data; class Test { public function __construct() { $pageController = new \Project\Data\Controller\Page; $pageModel = new \Project\Data\Model\Page; } } ?>
kabnhiende