Skip to main content

Namespaces in php

Trushi Jasani
EditReport

Namespaces allow you to organize your code into logical groups and avoid naming conflicts between classes, functions, and constants.

Why Use Namespaces?​

Without namespaces, if two libraries both define a class named User, there would be a conflict. Namespaces solve this:

// Library A
namespace LibraryA;
class User { ... }

// Library B
namespace LibraryB;
class User { ... }

Defining a Namespace​

A namespace declaration must be the first statement in a php file:

<?php
namespace App\Models;

class User {
public string $name;

public function __construct(string $name) {
$this->name = $name;
}
}
?>

Using a Namespaced Class​

<?php
require 'User.php';

$user = new App\Models\User("Alice");
echo $user->name; // Alice
?>

The use Keyword​

Import a class so you don't need the full path every time:

<?php
use App\Models\User;

$user = new User("Alice");
echo $user->name;
?>

Aliasing with as​

<?php
use App\Models\User as AppUser;
use Admin\Models\User as AdminUser;

$u1 = new AppUser("Alice");
$u2 = new AdminUser("Bob");
?>

Nested Namespaces​

You can nest namespaces using backslash as a separator:

<?php
namespace App\Controllers\Auth;

class LoginController {
public function login() {
echo "Logging in...";
}
}
?>
<?php
use App\Controllers\Auth\LoginController;

$ctrl = new LoginController();
$ctrl->login();
?>

Global Namespace​

To access a class or function from the global namespace inside a namespaced file, prefix it with \:

<?php
namespace App;

class Database {
public function connect() {
$pdo = new \PDO("sqlite::memory:"); // global PDO class
}
}
?>

Namespaces and Functions / Constants​

<?php
namespace MathUtils;

const PI = 3.14159;

function square($n) {
return $n * $n;
}
?>
<?php
use const MathUtils\PI;
use function MathUtils\square;

echo PI; // 3.14159
echo square(4); // 16
?>

Multiple Namespaces in One File​

Possible but generally not recommended:

<?php
namespace First;
class MyClass {}

namespace Second;
class MyClass {}
?>

Autoloading with Namespaces (PSR-4)​

Modern php uses Composer and PSR-4 autoloading to automatically load classes based on their namespace:

composer.json:

{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}

With this setup, App\Models\User would map to src/Models/User.php.

<?php
require 'vendor/autoload.php';

use App\Models\User;

$user = new User("Alice");
?>

Tip: Following PSR-4 conventions and using Composer autoloading is the standard way to organize php projects with namespaces.

Finished reading? Mark this topic as complete.