Introduction to Namespaces
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 10 of 91.
As your PHP projects grow, you'll create many classes. What happens when two classes have the same name?
For example, you might have a User class for your blog and another User class for your shop. Namespaces solve this problem by organizing classes into logical groups.
A namespace is like a folder for your classes. You declare it at the top of your PHP file using the namespace keyword:
<?php
namespace Blog;
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
Now you can have another User class in a different namespace:
<?php
namespace Shop;
class User {
public $email;
public function __construct($email) {
$this->email = $email;
}
}
To use a namespaced class, you reference it with its full path using a backslash:
<?php
$blogUser = new \Blog\User("Alice");
$shopUser = new \Shop\User("alice@example.com");
echo $blogUser->name . "\n";
echo $shopUser->email . "\n";
Output:
Alice
alice@example.com
The backslash \ separates namespace levels, similar to how slashes separate folders in a file path. You can also create nested namespaces like App\Models\Blog for deeper organization.
Key Point: Namespaces prevent naming conflicts and keep your code organized. Always declare the namespace before any other code in your file (except for declare statements).
Challenge
EasyLet's organize a small application using namespaces to prevent naming conflicts between classes with the same name.
Imagine you're building a system that handles both vehicles and animals. Both domains have an entity called Car — one represents an actual automobile, while the other is a pet cat named "Car" (yes, some people name their cats that way!).
You'll create three files:
Vehicle/Car.php— Define aCarclass in theVehiclenamespace with apublic $brandproperty. The constructor should accept the brand name and set it. Add adescribe()method that returns"Vehicle: [brand]".Animal/Car.php— Define aCarclass in theAnimalnamespace (this is a cat named Car!). It should have apublic $ageproperty. The constructor accepts the age and sets it. Add adescribe()method that returns"Cat named Car, age: [age]".main.php— Include both class files usingrequire_once. Create one object from each namespace using their full namespace paths, then print the result of callingdescribe()on each object (each on its own line).
In main.php, create:
- A
Vehicle\Carwith brand"Toyota" - An
Animal\Carwith age3
Remember to use the backslash \ to reference namespaced classes with their full path when creating objects.
Cheat sheet
Namespaces organize classes into logical groups and prevent naming conflicts when multiple classes share the same name.
Declare a namespace at the top of a PHP file using the namespace keyword:
<?php
namespace Blog;
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
You can have classes with the same name in different namespaces:
<?php
namespace Shop;
class User {
public $email;
public function __construct($email) {
$this->email = $email;
}
}
To use a namespaced class, reference it with its full path using a backslash \:
<?php
$blogUser = new \Blog\User("Alice");
$shopUser = new \Shop\User("alice@example.com");
echo $blogUser->name . "\n";
echo $shopUser->email . "\n";
The backslash separates namespace levels, similar to folder paths. You can create nested namespaces like App\Models\Blog.
Important: Always declare the namespace before any other code in your file (except declare statements).
Try it yourself
<?php
// Include the class files
require_once 'Vehicle/Car.php';
require_once 'Animal/Car.php';
// TODO: Create a Vehicle\Car object with brand "Toyota"
// Remember to use the full namespace path with backslash
// TODO: Create an Animal\Car object with age 3
// Remember to use the full namespace path with backslash
// TODO: Print the result of describe() for 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