HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Namespaces

Namespaces are a way of grouping related classes, interfaces, functions, and constants. They solve a major problem in large PHP applications: **Name Collisions**. They allow you to have two classes with the same name as long as they are in different namespaces.


Why Use Namespaces?

Imagine you are using two different external libraries. Both libraries have a class named User. Without namespaces, PHP wouldn't know which one you want to use, and your script would crash with a "Cannot redeclare class" error.

Namespaces are like **folders** on your computer. You can have two files named index.php as long as they are in different folders. Namespaces bring this same logic to your PHP code.

Key Benefit: Namespaces make your code much more organized and allow you to use short, descriptive class names without worrying about global conflicts.

Defining a Namespace

A namespace must be declared at the **very top** of a PHP file, before any other code (except for a possible declare statement).

<?php
    namespace App\Models;

    class User {
        public function getName() {
            return "John Doe";
        }
    }
?>

Using a Namespaced Class

To use a class that is inside a namespace, you have three options:

1. Fully Qualified Name

Access the class by its full "path" every time you use it.

<?php
    $user = new \App\Models\User();
?>

2. The use Keyword

Import the namespace at the top of your file. This is the most common and recommended way.

<?php
    use App\Models\User;

    $user = new User(); // Now you can use the short name
?>

3. Aliasing with 'as'

If you have two classes with the same name from different namespaces, you can give one of them an "alias".

<?php
    use App\Models\User as LocalUser;
    use ExternalLib\User as RemoteUser;

    $user1 = new LocalUser();
    $user2 = new RemoteUser();
?>

Practical Example: Organizing Code

Namespaces are often structured to match your folder structure (following the PSR-4 standard). For example:

  • namespace App\Controllers; (Stored in /src/Controllers/)
  • namespace App\Models; (Stored in /src/Models/)
  • namespace App\Helpers; (Stored in /src/Helpers/)
Note: PHP uses the backslash (\) as a separator for namespaces, not a forward slash.

Summary

  • namespace keyword defines a virtual folder for your code.
  • Must be at the top of the file.
  • Solves name collisions between different libraries or modules.
  • use keyword makes it easier to reference namespaced classes.
  • as keyword provides aliases to resolve duplicate names.
Pro Tip: When using namespaces, you can access global PHP classes (like Exception or DateTime) by putting a backslash in front of them (e.g., new \Exception()) if you are inside a namespace.