Advanced PHP: Namespaces

Learn how to organize and scope your PHP code using namespaces—essential for larger applications and avoiding naming conflicts.

1. What Are Namespaces?

Namespaces are qualifiers that let you group related code (classes, functions, constants, interfaces, traits, enums) and avoid name collisions when multiple scripts use the same identifiers.

<?php
namespace Library\Utils;

class Logger {
    public function log($msg) {
        echo "[Library] " . $msg;
    }
}

namespace App;

class Logger {
    public function log($msg) {
        echo "[App] " . $msg;
    }
}

// Using both classes:
$libLogger = new \Library\Utils\Logger();
$appLogger = new \App\Logger();

$libLogger->log("Loaded library module.");
$appLogger->log("Started app.");
?>
    

2. Declaring Namespaces

Use the `namespace` keyword at the very beginning of your file (before any PHP code, except `declare()`).

// File: src/Math.php
<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
        

3. Accessing Namespaced Code

If you’re within the same namespace, refer to classes and functions directly. To use code from another namespace, prefix with its namespace.

// In namespace Html:
<?php
namespace Html;

class Table { /* ... */ }
$table = new Table();

// Outside the namespace:
$table = new Html\Table();
?>
        

4. Name Resolution: Unqualified, Qualified, Fully‑qualified

PHP resolves names like file paths:

  • Unqualified: Foo → refers to current namespace’s Foo
  • Qualified: Sub\Foo → if in NS, resolves to NS\Sub\Foo
  • Fully‑qualified: prefix with a leading backslash (\NS\Foo) → literal global path.
<?php
namespace MyApp;

class Foo {
    public static function who() {
        echo "I'm MyApp\\Foo";
    }
}

namespace MyApp\Sub;

class Foo {
    public static function who() {
        echo "I'm MyApp\\Sub\\Foo";
    }
}

namespace {
    use MyApp\Foo;           // Unqualified: resolves to MyApp\Foo
    use MyApp\Sub\Foo as SubFoo;  // Qualified
    use \MyApp\Sub\Foo;      // Fully-qualified with backslash

    Foo::who();              // → I'm MyApp\Foo
    SubFoo::who();           // → I'm MyApp\Sub\Foo
    \MyApp\Sub\Foo::who();   // → I'm MyApp\Sub\Foo
}
?>
    

5. Nested Namespaces

You can declare deeper namespaces using backslashes:

<?php
namespace MyApp\Utilities;

class Helper {}
?>
        

Use the full path to access:

<?php
$h = new \MyApp\Utilities\Helper();
?>
        

6. Aliasing with use

To shorten long namespaces or class names:

<?php
use Html\Table as T;

$table = new T();
?>
        

7. Namespace Declaration Rules

  • Only one namespace declaration per file, unless using bracketed syntax.
  • No code (except comments or `declare`) before namespace.
  • Works across multiple files — namespace is a logical grouping, not a file constraint.
  • Affects only classes, interfaces, functions, constants; not variables.
<?php
declare(strict_types=1);

namespace App\Utils;

class Formatter {
    public static function slugify(string $text): string {
        return strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $text), '-'));
    }
}

namespace Main;

use App\Utils\Formatter;

echo Formatter::slugify("Hello World!");
?>