PHP Use Keyword: Importing and Aliasing Namespaces
This article explains how to use the use keyword in PHP
to import and alias namespaces. You will learn how to simplify your code
by importing classes, interfaces, functions, and constants, as well as
how to resolve naming conflicts using the as keyword for
aliasing.
Importing Namespaces and Classes
In PHP, namespaces prevent name collisions between classes. However,
writing out fully qualified class names (e.g.,
\Database\Connection\MySQLDriver) makes code verbose and
hard to read.
To import a namespace or class, place the use keyword at
the top of your PHP file, after the namespace
declaration.
<?php
namespace App\Controllers;
// Import the class
use App\Services\Mailer;
class UserController
{
public function register()
{
// You can now instantiate Mailer directly without its full namespace
$mailer = new Mailer();
}
}Once imported, you can refer to the class by its unqualified name
(Mailer) instead of its fully qualified name
(\App\Services\Mailer).
Aliasing Namespaces and Classes
When you have two classes with the exact same name from different
namespaces, importing both directly will cause a PHP fatal error. To
resolve this conflict, use the as keyword to create an
alias (a nickname) for one or both classes.
<?php
namespace App\Controllers;
use LibraryA\User as LibraryUser;
use LibraryB\User as LocalUser;
class AuthController
{
public function login()
{
// Use the aliases to avoid naming conflicts
$userA = new LibraryUser();
$userB = new LocalUser();
}
}Grouping Imports
If you need to import multiple classes from the same namespace, you can group them together inside curly braces to keep your code clean and concise.
<?php
namespace App;
// Grouped import
use App\Models\{User, Post, Comment};
class DashboardController
{
public function index()
{
$user = new User();
$post = new Post();
$comment = new Comment();
}
}Importing Functions and Constants
The use keyword is not limited to classes. You can also
import external functions and constants by prefixing the
use keyword with function or
const.
<?php
namespace App;
use function App\Helpers\format_date;
use const App\Config\MAX_LIMIT;
class Report
{
public function generate()
{
// Call the imported function
$date = format_date(time());
// Use the imported constant
$limit = MAX_LIMIT;
}
}