Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







namespace vs use in PHP


Why namespace And use Keywords Used In PHP


20th May 2020 5 mins read
Share On     Share On WhatsApp     Share On LinkedIn


Hello friends! In this article you will learn the difference between use & namespace in PHP.


Contents


  1. Why To Use namespace
  2. namespace Syntax
  3. Solving Problem (Global Namespace & Custom Namespace)
  4. use Syntax (For Aliasing / Importing)
  5. Why To Use use With Examples

Prerequisites


Basic knowledge of PHP & PHP OOPS concepts.


1) Why To Use namespace


As per PHP documentation namespaces are designed to solve two problems when creating re-usable code elements such as classes or functions:


  1. Name collisions between code you create, and internal PHP classes / functions / constants or third-party classes / functions / constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to the first problem, improving readability of source code.


Now days many of us are using open source or custom built packages in our projects instead of writing it from scratch for example ExcelSheet, PDF, Email, FileSystem to name few.


Consider we have a User class for our project to handle users login, logout, registration details.


Path: classes/User.php

class User
{
    /** User methods implmentation */
}


And couple of weeks later you need some package for example auth package which may internally has User class as follows


Path: packages/auth/User.php

class User
{
    /** Auth Package User Implementation  */
}


And at some point you want to use both of User class in another class as shown below then you will get error


Example: index.php

<?php
/** For debugging purpose */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

/** Use Auth class */
require_once './classes/User.php';
require_once './packages/auth/User.php';

/** Other usage code goes here */


The above will throw error because User classes has been redeclared. These are called as name collision.


Fatal error: Cannot declare class User, because the name is already in
use in /Applications/MAMP/htdocs/test/packages/auth/User.php on line 2



namespace To Rescue


This is where namespace comes to rescue. By using namespace we can avoid class, interface and constants collisions.


NOTE: By default everything will be in global namespace.You will learn more on global namespace and custom namespace in upcoming sections.

2) namespace Syntax


The following is the basic syntax of namespace. Usually you write namespace on the first line after opening the PHP tag in file. The path_of_file will be usually Pascal case (ie every word starts with capital word, similar to your class names)


Syntax

<?php

namespace path_of_file;

class class_name 
{

}

3) Solving Problem (Global Namespace & Custom Namespace)


Custom Namespace


As I had told you that by default all the classes will be in global namespace if you don't specify any namespace to them.


In the following code I have used Classes as the namespace which will override the global namespace and get it resolved


classes/User.php class

<?php 

namespace Classes;

class User
{
    /** User methods implmentation */
}



In the following code I have used Packages as the namespace which will override the global namespace and get it resolved


packages/User.php class

<?php 

namespace Packages;

class User
{
    /** User methods implmentation */
}


To use both the User classes in same file is bit tricker but very easy to understand. Check the following example code

index.php class

<?php
use Classes\User;
use Packages\Auth\User as PackagesUser;


require_once './classes/User.php';
require_once './packages/auth/User.php';


$classUser = new User();


$packageUser = new PackagesUser();


Observe the following 2 lines in the above code. I have used use keyword more on that you will learn in next section


use Classes\User;
use Packages\Auth\User as PackagesUser;


Since both the class names (ie classes/User.php & packages/Auth/User.php) are of User we can use only one User class in index.php file. And I have resolved it by using alias names.
This is what use is used to alias the names of the same classes.


More on use you will learn in next section.


Global Namespace Usage In Your Class (with \ or use)


Some times along with the Custom Namespace you might have requirement to use Global Namespace


If you try to use the new DateTime() PHP Object normally in Classes namespace then you will get error. Let me give you demo.


Product.php

<?php

namespace Classes;

class Product
{
    public function store()
    {
        /** THIS LINE THROWS ERROR AS DateTime() is not found 
           within Classes namespace */
        $dateTime = new DateTime();
    }
}


Since the namespace is in Classes PHP will check if any DateTime() function is written in our custom namespace instead of global namespace. As DateTime() is in PHP global namespace.


Fatal error: Uncaught Error: Class 'Classes\DateTime' not found in 
/Applications/MAMP/htdocs/test/classes/product.php:7 Stack trace: #0 {main} 
thrown in /Applications/MAMP/htdocs/test/classes/product.php on line 7


To resolve that we can do it by ( \ or use keyword as shown in the following examples)


Using use keyword


<?php

namespace Classes;

/** OBSERVE THIS LINE */
use DateTime;

class Product
{
    public function store()
    {
        /** OBSERVE THIS LINE */
        $dateTime = new DateTime();
    }
}


In Simple Words: As you see from the above code DateTime() is in global namespace of PHP as we have redeclared the scope of DateTime to global with use DateTime;



Using (\)


One and the same as above with just minor change ie I am using new \DateTime(). You can follow this approach when you have to write once. But I highly encourage you to go ahead with use keyword.


<?php

namespace Classes;

class Product
{
    public function store()
    {
        /** OBSERVE THIS LINE BackSlash ( \ ) 
          with tell to use from global Namespace */
        $dateTime = new \DateTime();
    }
}

4) use Syntax (For Aliasing / Importing)


The "use" keyword tells PHP that you are using a specific file or dependency (it can be a class, trait, interface etc)


Importing With Auto Alias


/* For importing file and directly use with that filename */
use namespace_of_file;


Example:


/** Here the PHP will default alias it to User */
use Classes\User;

Importing With Manual Aliasing


/** Used for aliasing the same used classes or for better understanding */
use namespace_of_file as alias_name;


Example:


/** Here I have imported and renamed it to PackagesUser */
use Packages\Auth\User as PackagesUser;

5) Why Do We Use use With Example


As you saw in the earlier example we have used use to rename the same classname.


/* Here by default it has aliased to User 
   so we can directly use as User */
use Classes\User;

/** Here we are renaming manually */
use Packages\Auth\User as PackagesUser;


If you have not used the same class name for namespace then no need to alias with as keyword like the following example


use Classes\User;
use Packages\Excelsheet\Excel;

$classUser = new User();

$excel     = new Excel();


The same can be written without use as follows


$classUser = new \Classes\User();

$excel     = new \Packages\ExcelSheet\Excel();

Conclusion


Hope you understood the difference between use & namespace keywords. If any doubts kindly drop me message in the below comment box.







Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing