Sobes.tech
Junior

What is the purpose of using namespaces in PHP?

sobes.tech AI

Answer from AI

Namespaces in PHP are used for:

  1. 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.
  2. Autoloading: They simplify the process of autoloading classes by linking directory structures with namespace hierarchies.
  3. Improving code readability: They make it clear which part of the code a particular element belongs to.
  4. 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();