The Use Command and Namespaces in OOP in PHP
Let us have the following class Data:
<?php
namespace \Core\Admin;
class Data
{
public function __construct($num)
{
}
}
?>
Let there also be a class Page that creates
objects of the Data class inside itself:
<?php
namespace Users;
class Page
{
public function __construct()
{
$data1 = new \Core\Admin\Data('1');
$data2 = new \Core\Admin\Data('2');
}
}
?>
As you can see, both of our classes are in
completely different namespaces, so
calls to the Data class cannot be simplified,
similar to how we did it in the previous
lesson. However, these calls are very long
and inconvenient, because in each call to the
Data class, its long
namespace has to be specified.
To solve this problem, there is a
special command use. Using
this command, it is enough to connect the
class by its full name once, and after that
it will be possible to refer to this class simply
by the class name. See the example:
<?php
namespace Users;
use \Core\Admin\Data; // connect the class
class Page extends Controller
{
public function __construct()
{
$data1 = new Data('1'); // call simply by name
$data2 = new Data('2'); // call simply by name
}
}
?>
Simplify the following code using
use:
<?php
namespace Project;
class Test
{
public function __construct()
{
// Create 3 objects of the same class:
$data1 = new \Core\Users\Data('user1');
$data2 = new \Core\Users\Data('user3');
$data3 = new \Core\Users\Data('user3');
}
}
?>
The following classes are given:
<?php
namespace Core\Admin;
class Controller
{
}
?>
<?php
namespace Users;
class Page extends \Core\Admin\Controller
{
}
?>
Simplify the class inheritance code by applying
the use command.