Namespaces
Last updated
What is Namespaces?
Namespaces in PHP are a way of encapsulating items so that name collisions won't occur. When your code expands, there could be a situation where classes, interfaces, functions, or constants might have the same name, causing confusion or errors. Namespaces come to the rescue by grouping these items. You declare a namespace using the keyword 'namespace' at the top of your PHP file. Every class, function, or variable under this declaration is a part of the namespace until another namespace is declared, or the file ends. It's like creating a new room in your house solely for storing sports equipment. This makes it easier to find your tennis racket, as you won't have to rummage around in a closet full of mixed items.
Here's a quick example:
namespace MyNamespace\SubNamespace;
function displayGreeting() {
echo 'Hello World!';
}
Free resources to learn Namespaces
- Official docsNamespaces
More in stage 12: PHP-FIG
Namespaces: common questions
Can I learn Namespaces in Hindi?
This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Namespaces in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.
Is this Namespaces tutorial for beginners?
It is lesson 87 of 120 in the free PHP roadmap, in stage 12, PHP-FIG. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.