The use Keyword
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 11 of 91.
Writing the full namespace path every time you use a class can get tedious. The use keyword lets you import a class at the top of your file, so you can reference it by its short name.
Instead of writing \Blog\User repeatedly, you can import it once:
<?php
use Blog\User;
$user = new User("Alice");
echo $user->name;
When you need classes from different namespaces with the same name, you can create an alias using the as keyword:
<?php
use Blog\User as BlogUser;
use Shop\User as ShopUser;
$blogger = new BlogUser("Alice");
$customer = new ShopUser("alice@example.com");
echo $blogger->name . "\n";
echo $customer->email . "\n";
Output:
Alice
alice@example.com
You can also import multiple classes from the same namespace using grouped imports:
<?php
use Blog\{User, Post, Comment};
$user = new User("Alice");
$post = new Post("Hello World");
Key Point: The use statement must appear after the namespace declaration (if any) and before any other code. It makes your code cleaner and easier to read by eliminating repetitive namespace paths.
Challenge
EasyLet's organize a messaging application using the use keyword to import classes cleanly and avoid writing full namespace paths everywhere.
You'll create three files that work together:
Messaging/Email.php— Define anEmailclass in theMessagingnamespace. It should have apublic $addressproperty, a constructor that accepts and sets the address, and asend()method that returns"Sending email to [address]".Messaging/SMS.php— Define anSMSclass in theMessagingnamespace. It should have apublic $phoneproperty, a constructor that accepts and sets the phone number, and asend()method that returns"Sending SMS to [phone]".main.php— Include both class files, then use theusekeyword to import both classes. Create anEmailobject with address"alice@example.com"and anSMSobject with phone"555-1234". Print the result of callingsend()on each object (each on its own line).
In main.php, instead of writing new \Messaging\Email(...), you'll import the classes at the top with use statements so you can simply write new Email(...) and new SMS(...).
Cheat sheet
The use keyword imports a class at the top of your file, allowing you to reference it by its short name instead of the full namespace path:
<?php
use Blog\User;
$user = new User("Alice");
When classes from different namespaces share the same name, create an alias using the as keyword:
<?php
use Blog\User as BlogUser;
use Shop\User as ShopUser;
$blogger = new BlogUser("Alice");
$customer = new ShopUser("alice@example.com");
Import multiple classes from the same namespace using grouped imports:
<?php
use Blog\{User, Post, Comment};
$user = new User("Alice");
$post = new Post("Hello World");
The use statement must appear after the namespace declaration (if any) and before any other code.
Try it yourself
<?php
// Include the class files
require_once 'Messaging/Email.php';
require_once 'Messaging/SMS.php';
// TODO: Use the 'use' keyword to import both classes from the Messaging namespace
// This allows you to write 'new Email(...)' instead of 'new \Messaging\Email(...)'
// TODO: Create an Email object with address "alice@example.com"
// TODO: Create an SMS object with phone "555-1234"
// TODO: Print the result of calling send() on each object (each on its own line)
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern