Junior
What are namespaces in PHP?
sobes.tech AI
Answer from AI
Namespaces in PHP are a way to encapsulate elements such as classes, interfaces, functions, and constants to prevent name conflicts and organize code. They solve the problem that arises when two different developers use the same name for an element (for example, a class named Logger), which would lead to a fatal error "Cannot redeclare class" without using namespaces.
How it works:
- A namespace is declared at the beginning of a file using the
namespacekeyword. - Elements defined within this file belong to the declared namespace.
- To access elements from another namespace, the fully qualified name (FQN) is used, which includes the namespace name and the
\separator. - You can import individual elements or entire namespaces using the
usekeyword to use them without specifying the full qualified name.
Example of usage:
// File src/Utils/Logger.php
<?php
namespace App\Utils;
class Logger
{
public function log(string $message): void
{
echo "LOG: " . $message . "\n";
}
}
// File src/Services/UserService.php
<?php
namespace App\Services;
use App\Utils\Logger; // Import Logger class
class UserService
{
private Logger $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function createUser(string $username): void
{
// Using the imported class by its short name
$this->logger->log("Creating user: " . $username);
// ... user creation logic
}
}
Without use, you would have to write new \App\Utils\Logger().
Namespaces help create modular, easily maintainable, and scalable code, especially in large projects. They are the foundation of PSR-4 (Autoloading Standard), which regulates how classes should be organized in files according to their namespaces.