Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

PHP Namespaces

Namespaces prevent naming conflicts between classes, functions, and constants in large projects. They work like directories for your code.

Declaring Namespaces

The namespace declaration must be the first statement in a file (before any code except declare).

Namespace Declaration
<?php
// File: src/Database/Connection.php
namespace App\Database;

class Connection {
    private static ?\PDO $pdo = null;

    public static function get(): \PDO {
        if (self::$pdo === null) {
            self::$pdo = new \PDO("mysql:host=localhost;dbname=myapp", "root", "");
        }
        return self::$pdo;
    }
}

// File: src/Models/User.php
namespace App\Models;

class User {
    public int $id;
    public string $name;

    public function __construct(int $id, string $name) {
        $this->id   = $id;
        $this->name = $name;
    }
}

// File: src/Services/UserService.php
namespace App\Services;

// Nested namespace
namespace App\Services\Auth;

class AuthService {
    public function login(string $user, string $pass): bool {
        return $user === "admin" && $pass === "secret";
    }
}
?>

use Keyword and Aliases

Import classes from other namespaces with use. Create aliases with as to avoid conflicts.

use and Aliases
<?php
namespace App;

// Import specific classes
use App\Database\Connection;
use App\Models\User;
use App\Services\Auth\AuthService;

// Alias to avoid name conflicts
use App\Models\User as UserModel;
use SomeOtherLib\User as LibUser;

// Import multiple from same namespace (PHP 7+)
use App\Models\{User, Post, Comment};

// Use in code
$conn = Connection::get();
$user = new UserModel(1, "Alice");
$auth = new AuthService();

if ($auth->login("admin", "secret")) {
    echo "Logged in as " . $user->name;
}

// Global namespace — prefix with backslash
$date = new \DateTime(); // PHP's built-in DateTime
echo $date->format("Y-m-d");
?>

Autoloading with Composer

Modern PHP uses Composer's PSR-4 autoloader so you never need to manually require class files.

Composer Autoloading
// composer.json
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

// After running: composer dump-autoload
// In your entry point (index.php):
require_once 'vendor/autoload.php';

use App\Models\User;
use App\Database\Connection;

// Classes are loaded automatically — no require needed!
$user = new User(1, "Alice");
echo $user->name;

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.