Web Programming TutorialsNamespaces in PHP

Namespaces in PHP

Today we will learn about a new concept called namespaces in PHP in this PHP Namespaces tutorial.

  • Namespace is a new concept in PHP which was introduced in PHP version 5.3.
  • Namespace is a container used to group classes, interfaces, constants, functions, etc.
  • It is used for proper organization of the data and also to avoid naming conflicts.
  • Till now we were unable to name two classes with same name in PHP, but we can make it possible using namespaces. Two different namespaces can have classes with same name without any conflict.
  • In a large application, we can group related classes, interfaces, etc. in respective namespaces and use them accordingly whenever required.
  • The classes in different namespaces are accessed with the respective namespace name.
  • For example: if class first is defined in namespace ABC and another class with name first is defined in namespace EFG, then both the classes can be accessed as ABC\first and EFG\first.
  • The languages like java, dotnet already have namespace concept in the form of packages and namespaces.
  • We will learn how to use namespaces step by step.
  • Defining a Namespace:
    • To use a namespace, we first have to define it. To define a namespace, we have to use a keyword namespace followed by its name.
    • The definition of namespace should be the first statement in a PHP file.
    • The namespace name should follow the same rules as the name of any function or class. I mean, it can start with a letter or an underscore and can contain any number of letters, numbers etc.
    • We can define namespaces in two ways:
    • First way:
    • <?php
      	namespace Web;
      	//a class, function, etc. here
    • Here, we write the keyword namespace and its name following it with semicolon at the end.
    • All the code written below this namespace definition is grouped inside this namespace Web.
    • Second way:
    • <?php
      	namespace Website
      	//a class, function, etc. here
    • In this second way of namespace definition, we use curly braces in it.
    • The namespace keyword with its name is followed by curly braces. The code in curly braces is grouped inside the namespace Website.
    • These are the 2 ways of defining namespaces. You can choose anyone.
    • If you want to assign a code block to a global space, you can write this code block in a namespace without name. See the code below:
    • <?php
      		//code here
    • This global namespace can be defined using the second way of defining namespaces.
  • Defining Sub-Namespaces:
    • We can have a namespace inside another namespace. You can imagine this just like a folder inside another folder and any hierarchy of such folders is allowed.
    • Sub namespaces inside a namespace is defined by using a backslash between the namespaces.
    • Let us see this example:
    • <?php
      	namespace Website\hospital\medicine;
      	//code here
    • Here we have defined a sub-namespace in the statement
      namespace Website\hospital\medicine;
    • Here, Website is a namespace which has a namespace hospital inside it and in turn it has a namespace medicine inside it. All these namespaces are separated by a backslash (\).
    • The code written below the definition will be grouped inside the medicine namespace.
  • Multiple namespaces:
    • You can have multiple namespaces in a PHP file as shown below:
    • <?php
      	namespace N1;
      	// code for namespace N1
      	namespace N2;
      	//code for namespace N2
      	Namespace N3;
      	//code for namespace N3
    • The code followed by the namespaces is included in that namespaces itself. I mean the code below namespace N1 is included in namespace N1, code below namespace N2 is included in namespace N2 and so on.
    • But if we are defining classes in the code, it is not a good practice to have more than one class in one file. But you can do this using multiple namespaces by having one class in each namespace.
  • Using Namespace:
    • We can use the defined namespace in another program by calling them in 3 ways:
      • Using unqualified name.
      • Using qualified name.
      • Using fully qualified name.
    • Unqualified name: unqualified name means referring the file name in the current namespace. If we have a namespace Classes with a class C1 in it, we can refer it directly in the current namespace classes as $c=new C1(); this resolves to Classes\C1.
    • Qualified name: qualified name means referring the file name in the sub-namespace of the current namespace. If we have a namespace Customer inside the namespace Service and we have a class Provide in namespace Customer and if we refer it from namespace Service as $s=new Customer\Provide(); this resolves to Service\Customer\Provide.
    • Fully qualified name: fully qualified name means referring any file in any namespace. Here, if we want to refer the class Provide discussed about in above point in some another namespace, we can refer it as $p=Service\Customer\Provide(); this resolves to Service\Customer\Provide.
    • Thus we can access any class, interface, etc. from or in any namespace by using its unqualified or qualified or fully qualified names.
    • Let us see an example:
    • To demonstrate the example, create a new folder named namespace in the htdocs folder in xampp folder. Now open a new notepad++ document and save it as app.php in the newly created namespace folder. Now write the following code in app.php file:
    • <?php
      namespace Service;
      class Customer
      	function hello($str="Customer")
      		echo "Hello ".$str;
    • Here, we have defined a namespace named Service. The class Customer belongs to namespace Service. This means that the class Customer cannot be accessible anywhere without the namespace name Service.
    • The class contains a function named hello().
    • Now let us try to access the function hello() in another PHP file.
    • For this open a new notepad++ document and save it as index.php in the namespace folder itself. Now write the following code in the index.php file.
    • <?php
      	$c=new Service\Customer();
    • Here, we have linked our index.php file to app.php file using require_once() function, it connects/links the specified page to the current page.
    • Then we have created an object of Customer class using the statement $c=new Service\Customer();
    • Here we used the fully qualified name to access the Customer class.
    • Then using the object $c the function hello() is called.
    • When we run the script, the index.php page executes.
    • To run it, open your browser and type localhost/namespace in its address bar. The output is shown below:
    • output1
      fig 1

    • Here, we called the function in a class defined in app.php in index.php using its fully qualified name.
  • Using use keyword:
    • Imagine that you have your Customer class in CallCenter\ServiceProvider\Service namespace.
    • You would have to access this fully qualified name everywhere you would like to use the Customer class function.
    • It becomes very annoying if you have to write such a long path every time.
    • PHP has made it quite simple by using the use keyword.
    • You just have to put the namespace name following the use keyword at the top and then use the class name directly.
    • Write the following code in app.php file which includes sub-namespace as follows:
    • <?php
      namespace CallCenter\ServiceProvider\Service;
      class Customer
      	function hello($str="Customer")
      		echo "Hello ".$str;
    • Here, now our Customer class is inside the CallCenter\ServiceProvider\Service namespace.
    • Now let us access this class in index.php file. The code is shown below:
    • <?php
      	use CallCenter\ServiceProvider\Service\Customer;
      	$c=new Customer();
    • Here, we have used the keyword use to specify the namespace once in the file and then use the class in it only with its name. The use statement is shown below:
    • use CallCenter\ServiceProvider\Service\Customer;
    • Here, we have included also Customer in the namespace. Due to this we can directly create an object of Customer class as shown below:
    • $c=new Customer();
    • If we had written the use statement as follows:
      use CallCenter\ServiceProvider\Service; 

      we would have created the Customer object as shown below:

      $c=new Service\Customer();
    • We can even give a nickname to a long namespace using the use keyword. The modified code in index.php above is shown below:
    • <?php
      	use CallCenter\ServiceProvider\Service as Care;
      	$c=new Care\Customer();
    • Here, in the use statement shown below:
    • use CallCenter\ServiceProvider\Service as Care;
    • The namespace is given and a nickname Care is given to the long namespace using keyword as.
    • This nickname is used instead of the long namespace in creating the object of class Customer as shown below:
    • $c=new Care\Customer();
    • This use keyword makes our hard task very easy in just one statement.
    • Multiple use statements can be used in a program or the use keyword can also allow us to specify multiple namespaces separated by comma.
    • For example we have 2 namespaces with 2 different classes which we want to use in our script. The namespaces are CallCenter\ServiceProvider\Service and Employer\Employee. These namespaces can be specified using only one use statement as shown below:
    • use CallCenter\ServiceProvider\Service, Employer\Employee;
    • Thus multiple namespaces can be specified in s single use statement separated by comma.
    • We will get same output as in figure 1 for the above code.

Thus we successfully studied the concept of namespaces in this PHP Namespaces tutorial.

Previous articlePHP Form Email
Next articlePHP Cookies


Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article


More article

- Advertisement -Eduonix Blog