Back to results for “Namespaces”
PHP › Namespaces & Autoloading

What is a namespace in PHP, and what problem does it solve when working with larger applications or third party libraries?

Beginner

Answer

A namespace lets you group related classes, functions, and constants under a common named prefix, solving the problem of naming collisions that can occur when two different classes, perhaps from your own code and a third party library, happen to share the exact same class name, since namespaces let both classes coexist without conflict by qualifying each one with its own distinct namespace.
namespace App\Models;

class User {
}

// Used elsewhere as App\Models\User
Real-world example A project using both its own custom Logger class and a third party library's own separate Logger class avoids any naming conflict entirely, since each class lives within its own distinct namespace and can be referenced unambiguously.

Common follow-ups: What is the difference between a fully qualified class name and a relative class name?;How do namespaces relate to the actual folder structure of a project?