In this tutorial, we will learn about Namespaces in PHP. Namespaces are mainly used to group classes that perform some similar kind of task. Furthermore, another benefit to using namespaces is we can use the same name for more than one classes in different namespaces. For example, suppose we have namespaces A and B both can have a class with the name Example in them.
Page Contents
Declaring Namespace in PHP:
PHP we use the namespace keyword to Declaring Namespace. Just write the namespace keyword followed by the namespace name. Please check out the following example program.
<?php
namespace Bank;
?>
Please Note! declaring a namespace should be the first-line PHP file.
Namespace Example Program:
<?php
//declaring name space.
namespace SchoolNamespace;
class Student{
function showStudent()
{
echo 'Hello This showStudent method';
}
}
class Teacher{
function showTeacher()
{
echo 'Hello This showTeacher method';
}
}
?>
Using Namespaces:
We can use namespaces in two ways. From outside the namespace and within the namespace.
Accessing Namespace class from outside:
$student = new SchoolNamespace\Student()
Accessing class withing namespace:
All the files which follow namespace declaration can use all the classes that belong to that particular namespace.
<?php
namespace SchoolNamespace;
$student = new Student();
$teacher = new Teacher();
?>
Namespace Alias
We can give an alias to class or namespace. which makes it easy to use them while writing code. To proving alias we use two keywords use and as.
Giving a Namespace an alias:
use SchoolNamespace as SN;
$student = new Student();
$student->showStudent();
Giving a class an alias:
use SchoolNamespace\Student as S;
$student = new S();
$student->showStudent();
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
