</>
Skip to content
PHP lessons (41/49)

PHP — Namespaces

Basic namespace

<?php
namespace App\Models;

class User {
    public string $name;
}
?>

Using namespaces

<?php
use App\Models\User;
use App\Models\Product as P;

$user = new User();
$product = new P();
?>

Full qualified name

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

Namespace organization

src/
├── Models/
│   ├── User.php
│   └── Product.php
├── Controllers/
│   └── UserController.php
└── Services/
    └── EmailService.php

PSR-4 autoloading

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

Mini Practice

Write PHP code that:

  1. Defines a namespace
  2. Uses use statements
  3. Organizes code with namespaces
  4. Sets up PSR-4 autoloading

Up Next

In the next lesson, you'll learn about Type Hints — type declarations.

Related Topics

Frequently Asked Questions about Namespaces

What is Namespaces in PHP?

Namespaces is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Namespaces?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Namespaces.

Why is Namespaces important in PHP?

Namespaces is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.