Namespaces in PHP

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.

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();

 

Spread the love
Scroll to Top
×