What are namespaces in PHP, and what problem do they solve?

Last updated 15 June 2026

Namespaces are a way to encapsulate and group related classes, functions, and constants under a named scope, solving the problem of name collisions between code from different sources.

  • The problem they solve:

    • Without namespaces, two libraries each defining a Logger class would fatally collide.

    • They also let you avoid absurdly long prefixed names like MyApp_Db_Connection.

  • How they work:

    • Declared with namespace App\Service; at the top of a file.

    • You import names with use, optionally aliasing with as to resolve clashes.

    • A leading \ denotes the global namespace (e.g. \strlen()).

  • They pair directly with PSR-4 autoloading, mapping namespace to directory.

[lang:php] namespace App\Service; use Monolog\Logger as MonoLogger; class Logger {} // App\Service\Logger, no clash

  • https://www.php.net/manual/en/language.namespaces.global.php
All PHP interview questions