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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.