What are namespaces in PHP, and what problem do they solve?
Last updated
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
Loggerclass 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 withasto resolve clashes.A leading
\denotes the global namespace (e.g.\strlen()).
They pair directly with
PSR-4autoloading, mapping namespace to directory.
[lang:php]
namespace App\Service;
use Monolog\Logger as MonoLogger;
class Logger {} // App\Service\Logger, no clash