
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.
Hello friends! In this article you will learn the difference between use
& namespace
in PHP.
Contents
Basic knowledge of PHP & PHP OOPS concepts.
namespace
As per PHP documentation namespaces are designed to solve two problems when creating re-usable code elements such as classes or functions:
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
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.
namespace
SyntaxThe 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
{
}
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 ofUser
we can use only oneUser
class inindex.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.
\
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)
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;
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();
}
}
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)
/* 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;
/** 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;
use
With ExampleAs 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();
Hope you understood the difference between use
& namespace
keywords. If any doubts kindly drop me message in the below comment box.
Install RabbitMQ with Docker & Running with NodeJS
Getting Started With AMP (Accelerated Mobile Pages)
Website Speed and Performance Optimizations
Setup AMP (Accelerated Mobile Pages) In PHP Laravel
Create Zip File On The Fly With Streaming Download In PHP Laravel
Testing Laravel Emails With MailHog
Sass or SCSS @mixin vs @extends vs Placeholder (%)
SummerNote WYSIWYG Text Editor
Generate RSS Feeds in PHP Laravel
Automate Repeating Tasks In Linux Server With Cronjobs