Junior
What is the purpose of using namespaces in PHP?
sobes.tech AI
Answer from AI
Namespaces in PHP are used for:
- Preventing name collisions: When multiple libraries or parts of code use the same class, function, or constant names, namespaces help distinguish them from each other.
- Autoloading: They simplify the process of autoloading classes by linking directory structures with namespace hierarchies.
- Improving code readability: They make it clear which part of the code a particular element belongs to.
- Modularity: They allow organizing code into logical groups, enhancing project structure.
Example of usage:
<?php
namespace MyProject\Database;
class Connection {
// ...
}
namespace MyProject\Http;
class Request {
// ...
}
// In another file
use MyProject\Database\Connection;
use MyProject\Http\Request;
$db = new Connection();
$req = new Request();