Importing with use and Aliases

2.Importing with use and Aliases

M

In this chapter

We'll learn how use imports a class into a file under a short name, how as gives it an alias when two short names clash, how to import several classes at once, and how use function and use const import functions and constants — plus how this compares with imports in Java, Python and JavaScript.

12–14 min

The Problem in Real Life

The reminder script now spells every class in full: new \BookBay\Notifications\Notification(...), new \TextFlow\Sms\Client(...), \BookBay\Pricing\formatPrice(...). Twenty long names in forty lines.

Mia adds two lines at the top to shorten them: use BookBay\Notifications\Notification; and use TextFlow\Sms\Notification;. PHP refuses: "Cannot use TextFlow\Sms\Notification as Notification because the name is already in use".

M

I need both Notifications in this file. How do I give them short names that don't fight?

Mia

Full Names Everywhere vs. Short Names Imported Once

Long names everywhere

Fully qualified names are safe but noisy. Every line repeats BookBay\Notifications\…

A short name per file

use maps a short name to a full name — for this file only.

Two classes, one short name

When two imports would share a short name, an alias with as gives one of them a different one.

Importing with use and Aliases

Short names for long ones: namespaces make names unique, and use makes them comfortable again. This chapter covers:

  • use: importing a class, interface, trait or enum under its short name.
  • Aliases with as: a different short name, for clashes or clarity.
  • Group use: several imports from one namespace in one line.
  • use function and use const: importing functions and constants.
  • Other languages: Java, Python and JavaScript imports.

use: use BookBay\Notifications\Notification; near the top of a file means "in this file, Notification stands for BookBay\Notifications\Notification". Write use lines after the namespace line and before any code, one per class you need. Two things surprise people. First, use doesn't load anything — it only creates a short name; loading is the autoloader's job (chapter 6), and an import of a class that never gets used costs nothing. Second, imports apply to one file only: every file that needs the short name writes its own use line. The diagram below shows what an import really is: a line in the file's own little dictionary of names.

What use does: a short-name table for one file

use BookBay\Notifications\Notification;

Notification → BookBay\Notifications\Notification

use TextFlow\Sms\Notification as SmsNotification;

SmsNotification → TextFlow\Sms\Notification

later in the same file

new Notification(...)

PHP replaces it with the full name while compiling

new SmsNotification(...)

same: replaced with the full name

but

Another file

has its own table: without its own use lines, Notification means nothing there

Aliases with as: two imports can't share a short name — Mia's error. The fix is an alias: use TextFlow\Sms\Notification as SmsNotification; imports the class under a short name of your choosing. Now the file has Notification (BookBay's) and SmsNotification (TextFlow's). Aliases are also useful for clarity when a short name is too generic, like use TextFlow\Sms\Client as SmsClient;.

Mia's bug: two imports, one short name
<?php
namespace BookBay\Reminders;
use BookBay\Notifications\Notification;
use TextFlow\Sms\Notification; // the same short name again
// Fatal error: Cannot use TextFlow\Sms\Notification as Notification because the name is already in use
The fix: an alias with as
<?php
namespace BookBay\Notifications {
class Notification
{
public function __construct(public string $text) {}
}
}
namespace TextFlow\Sms {
class Notification
{
public function __construct(public string $to, public string $text) {}
}
}
namespace BookBay\Reminders {
use BookBay\Notifications\Notification;
use TextFlow\Sms\Notification as SmsNotification; // an alias
$ours = new Notification("Your booking is tomorrow.");
$sms = new SmsNotification("+447700900456", $ours->text);
echo get_class($ours), "\n"; // BookBay\Notifications\Notification
echo get_class($sms), "\n"; // TextFlow\Sms\Notification
}

Group use: several classes from the same namespace can be imported in one statement: use BookBay\Booking\{Booking, BookingStatus, GroupBooking};. It's the same as three use lines. Many teams prefer one class per line anyway, because it's easier to sort and to see in a code review; tools like PHP-CS-Fixer (Act 21) sort imports automatically.

use function and use const: plain use imports classes (and interfaces, traits and enums). Functions and constants need their own keyword: use function BookBay\Pricing\formatPrice; and use const BookBay\Pricing\VAT_PERCENT;. After that, formatPrice(2750) and VAT_PERCENT work as short names. The next chapter explains why functions and constants behave differently from classes even without an import.

Group use, use function and use const
<?php
namespace BookBay\Pricing {
const VAT_PERCENT = 20;
final class Money
{
public function __construct(public int $pence) {}
}
function formatPrice(int $pence): string
{
return "£" . number_format($pence / 100, 2);
}
}
namespace BookBay\Booking {
use BookBay\Pricing\{Money}; // group use (one class here)
use function BookBay\Pricing\formatPrice;
use const BookBay\Pricing\VAT_PERCENT;
$price = new Money(2750);
echo formatPrice($price->pence), " incl. ", VAT_PERCENT, "% VAT\n";
}
// £27.50 incl. 20% VAT

Imports in other languages: Java's import com.bookbay.booking.Booking; is the same idea as PHP's use: a short name per file, nothing extra loaded. Python's from bookbay.notifications import Notification as BookBayNotification also names things, but it runs the module the first time. JavaScript's import { Notification as SmsNotification } from "textflow-sms" loads the module too. PHP's use is the lightest of all: it's resolved while PHP compiles the file and costs nothing at runtime. The table below lists every form.

Table — Every form of use
FormExampleImports
Classuse BookBay\Booking\Booking;A class, interface, trait or enum
Aliasuse TextFlow\Sms\Notification as SmsNotification;The same, under another short name
Groupuse BookBay\Booking\{Booking, BookingStatus};Several classes from one namespace
Functionuse function BookBay\Pricing\formatPrice;A function
Constantuse const BookBay\Pricing\VAT_PERCENT;A constant
Function aliasuse function BookBay\Pricing\formatPrice as price;A function, renamed
Python: from … import … as … (it also runs the module)
# Python — import names AND load the module the first time
from bookbay.notifications import Notification
from textflow.sms import Notification as SmsNotification
ours = Notification("Your booking is tomorrow.")
sms = SmsNotification("+447700900456", ours.text)

Key Takeaway

use Full\Name\Class; gives a class (or interface, trait, enum) a short name in this file only; it loads nothing. When two imports share a short name, give one an alias with as. Group use imports several classes from one namespace in one line; use function and use const import functions and constants. Like Java's import, PHP's use is resolved at compile time and costs nothing at runtime — unlike Python's and JavaScript's imports, which also load code.

Why This Matters

The top of almost every PHP file in a modern project is a block of use lines: they're the file's list of everything it depends on. Reading them tells you, before any code, which parts of the project and which libraries a class uses.

Aliases are how real projects survive generic class names from different libraries: Request, Response, Client and Notification are everywhere, and as lets one file use several of them.

The reminder script imports both Notifications, one as SmsNotification, and reads cleanly again. Then Mia moves Booking into BookBay\Booking, and its isPast() method breaks: "Class "BookBay\Booking\DateTime" not found". Yet strlen() and sprintf() in the same file still work. That's the next chapter: how PHP resolves names.