Namespaces are like folders on your computer. They allow us to have multiple classes with the same name in the
same project without causing a conflict, because we separate them by their scope. This is crucial when using
external libraries or when working on larger projects.
Conflict Prevention: You can use multiple classes with the same name as long as they are in
different namespaces.
Better Organization: We logically divide the code into modules (e.g., Database, Users,
Store).
Shorter Names (Alias): By using "use", we can shorten long path names into simple
aliases.
EXAMPLE
RESULT
The result will be displayed here...
Key Rules to Follow:
Top of the File: A namespace must always be defined at the very beginning of the file.
Global Space: If you want to access built-in PHP functions or classes from within a
namespace, use a backslash (e.g., \Exception).
The use Keyword: Used to import a class so that we do not have to write the full path
every single time.
Simply put: namespaces ensure that your project remains clean and organized, even when it grows massive, and that
your classes do not "fight" each other due to identical names.
We use cookies to ensure a better user experience and website functionality.