LearnContact
Lesson 4919 min read

Namespaces

Learn how PHP namespaces prevent class and function name collisions as your codebase and its dependencies grow.

Introduction

Imagine your project defines a `User` class, and you also install a third-party library that happens to define its own `User` class. Without any way to tell them apart, PHP would not know which one you mean, and your application would break the moment both were loaded.

Namespaces solve this by giving classes, functions, and constants an address — a way of saying "this User belongs to my App\Models namespace" versus "that User belongs to the Vendor\Auth namespace." This lesson covers how to declare, import, and use namespaces.

What You Will Learn
  • The problem namespaces solve as codebases and dependencies grow.
  • How to declare a namespace with the `namespace` keyword.
  • How to import a namespaced class with `use`.
  • How to alias an imported class with `as`.
  • How namespaces relate to folder structure and autoloading.

The Problem Namespaces Solve

In a small script, having one class named `User` and one function named `validate()` is not a problem. But real applications grow, and they often pull in third-party libraries through Composer. Without namespaces, every class and function name in every library would have to be globally unique — an impossible constraint once you depend on dozens of packages.

A Familiar Analogy

Think of namespaces like folders on a filesystem. You can have a "photo.jpg" in your Vacation folder and a completely different "photo.jpg" in your Work folder — the folder gives each file a distinct full path, even though the filename alone is identical.

Declaring a Namespace

A namespace is declared with the `namespace` keyword, and it must be the very first statement in a PHP file (only a comment or the opening `<?php` tag may come before it).

User.php
<?php
namespace App\Models;

class User
{
    public function __construct(private string $name) {}

    public function getName(): string
    {
        return $this->name;
    }
}

This class's full, fully-qualified name is no longer just `User` — it is `App\Models\User`. Note that PHP uses a backslash (`\`) as the namespace separator.

Using a Namespaced Class

From outside the namespace, you can always refer to a class by its fully-qualified name.

index.php
<?php
require "User.php";

$user = new \App\Models\User("Amol");
echo $user->getName();
Output
Amol

The leading backslash before `App\Models\User` tells PHP to start resolving the name from the global namespace, which avoids ambiguity if the current file also has its own namespace declared.

Importing with use

Typing the fully-qualified name every time is tedious. The `use` keyword imports a namespaced class so you can refer to it by its short name for the rest of the file.

import-example.php
<?php
require "User.php";

use App\Models\User;

$user = new User("Priya");
echo $user->getName();
Output
Priya

Aliasing with as

When two classes from different namespaces share the same short name, or you simply want a clearer local name, use `as` to give the import an alias.

aliasing-example.php
<?php
namespace App\Models;
class User
{
    public function describe(): string { return "App Model User"; }
}

namespace Vendor\Auth;
class User
{
    public function describe(): string { return "Vendor Auth User"; }
}

namespace App;

use App\Models\User as UserModel;
use Vendor\Auth\User as AuthUser;

$model = new UserModel();
$auth = new AuthUser();

echo $model->describe() . "\n";
echo $auth->describe();
Output
App Model User
Vendor Auth User
Aliasing Avoids Collisions

Without aliasing, importing two different `User` classes from two namespaces into the same file would be impossible — `as` lets both coexist under distinct local names.

Namespaces and Folder Structure

By convention, modern PHP projects mirror their namespace structure with their folder structure. A class declared as `namespace App\Models;` typically lives at `app/Models/User.php`. This convention (called PSR-4) is what allows autoloaders to automatically find and load the correct file just from the class name, without you writing a manual `require` for every file.

NamespaceConventional File Path
App\Models\Userapp/Models/User.php
App\Controllers\HomeControllerapp/Controllers/HomeController.php
App\Services\PaymentServiceapp/Services/PaymentService.php
Looking Ahead

You do not need to build an autoloader by hand. Later lessons on Composer and Autoloading will show how PSR-4 autoloading automatically maps namespaces to file paths, so requiring dozens of files manually becomes unnecessary.

Common Mistakes

Avoid These Mistakes
  • Placing any code (other than a comment) before the `namespace` declaration, which causes a fatal error.
  • Forgetting the leading backslash when referring to a fully-qualified global class name.
  • Mismatching the namespace and the actual folder structure, breaking autoloading later.
  • Importing two classes with the same short name without aliasing one of them.

Best Practices

  • Always match your namespace structure to your folder structure, even before you introduce an autoloader.
  • Use one namespace declaration per file, placed at the very top.
  • Import classes you use often with `use` instead of repeating fully-qualified names.
  • Alias imports clearly (e.g. `as UserModel`) when names would otherwise collide.

Frequently Asked Questions

Can a single file declare multiple namespaces?

Technically yes using braces, but it is discouraged. The standard convention is one namespace per file, matching one class or a small set of related definitions.

What is the "global namespace"?

Code that has no namespace declaration lives in the global namespace. You can always reach it explicitly with a leading backslash, such as `\DateTime`.

Do namespaces affect performance?

No. Namespaces are purely an organizational tool resolved at compile time; they do not add any runtime overhead.

Can functions and constants have namespaces too?

Yes. Namespaces apply to classes, interfaces, traits, functions, and constants, not just classes.

Do I need Composer to use namespaces?

No, namespaces work with plain `require`/`include` too. Composer's autoloader just makes locating and loading namespaced files automatic and far more convenient.

Key Takeaways

  • Namespaces prevent class and function name collisions as a codebase and its dependencies grow.
  • A namespace is declared with `namespace App\Models;` as the first statement in a file.
  • The `use` keyword imports a namespaced class so you can refer to it by its short name.
  • The `as` keyword aliases an import to avoid collisions between similarly named classes.
  • Namespaces conventionally mirror folder structure, which autoloaders rely on to locate files.

Summary

Namespaces give every class, function, and constant a unique address, so your code and any third-party libraries you depend on can coexist without naming collisions.

In this lesson, you learned how to declare namespaces, import classes with `use`, alias imports with `as`, and how namespaces relate to the folder structure that autoloaders depend on. Next, you will learn about magic methods — special methods PHP calls automatically in certain situations.

Lesson 49 Completed
  • You understand the naming-collision problem namespaces solve.
  • You can declare a namespace and place a class inside it.
  • You can import and alias namespaced classes with use and as.
  • You know how namespaces relate to folder structure and autoloading.
Next Lesson →

Magic Methods