What is a namespace in PHP?

A namespace is a way to group classes, functions and constants under a name. It avoids name conflicts, when two libraries have a class with the same name, for example User or Logger.

Think of it like folders on your computer. Two files can have same name if they are in different folders.

<?php
namespace App\Models;

class User {
}

// ::class gives the full name including namespace
echo User::class;
?>

Output:

Tutorials Class - Output Window

App\Models\User

To use a class from another namespace, write its full name, or import it with the use keyword at the top of the file.

<?php
use App\Models\User;

$user = new User();
?>
Note: The namespace line must be the first statement in the file, only declare can come before it.

Learn more about the similar topics:
Tutorials
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?