In this tutorial, I'll go through the basics of namespaces in PHP. I'll explain why you might need namespaces, and I'll show you how to use PHP namespaces in your day-to-day development.
More often than not, you will end up using third-party libraries from different vendors in your PHP applications. Now, there could be collisions between two or more libraries if a library tries to reuse a name that's already being used by another library in your application. As you probably know, if you have a class, function, or constant declared somewhere in your code, you can't have another one with the same name elsewhere. If there’s a name collision, it’ll eventually break your application.
Before the introduction of namespaces in PHP, developers solved this problem by introducing different techniques that would prevent name collisions. One popular solution was to use long class and function names. For example, to introduce the Database
class in their library, they would prefix it with the vendor name, and thus it would become like Vendorname_Database
. If you’ve coded in WordPress or the Zend framework, I’m sure you've noticed such practices.
To address this problem, namespaces were introduced in PHP as of PHP 5.3. The best way to understand namespaces is by analogy to the directory structure concept in a filesystem. The directory which is used to group related files serves the purpose of a namespace. You can’t have two files with the same name in the same directory, but you can have files with the same name in different directories. Namespaces mimic the same principle in PHP!
Basically, namespaces provide a way to group related items together, avoiding any potential name collisions. Without a doubt, this has turned out to be one of the most significant recent changes in PHP. In fact, the majority of the third-party library vendors and frameworks have already adapted namespaces in their codebase.
That was a brief explanation of what namespaces are. We’ll see how to use them in the next couple of sections.
How Namespaces Work in PHP
In this section, you'll see how you could define a namespace and group related items under it.
Defining Namespaces and Sub-Namespaces
The first thing to do is to define a namespace with the namespace
keyword at the top of the PHP file. All the code underneath the namespace
keyword becomes namespaced code. It’s important to note that this keyword must be placed at the top of the file, making sure that nothing precedes it. The only exception is the declare
construct, which you can use before you define a namespace.
Let’s have a quick look at the following snippet, which demonstrates how to define a namespace.
<?php namespace Tutsplus; // code which is defined here belongs to the Tutsplus namespace ?>
As you can see, the above example defines the Tutsplus
namespace. The code which is defined after the namespace Tutsplus;
statement belongs to the Tutsplus
namespace. You can’t access this code directly the way we used to before namespaces were introduced. We’ll see how to call namespaced code in the next section.
To organize your code in a better way, PHP allows you to define a hierarchy of namespaces so that you can divide and organize your code logically: these are called sub-namespaces.
Let’s revise the previous example:
<?php namespace Tutsplus\Code; // code which is defined here belongs to the Tutsplus\Code namespace ?>
In the above example, the code belongs to the Tutsplus\Code
sub-namespace. In fact, you could define multiple sub-namespaces to divide your code across the library, e.g. Tutsplus\Code
, Tutsplus\Webdesign
, Tutsplus\Business
, etc.
In fact, you’ll find that developers always design the directory structure in a way which mimics and goes hand-in-hand with sub-namespaces. For example, the class Baz
which is defined under the Foo\Bar
namespace is supposed to be found under the Vendor\Foo\Bar
directory. Sub-namespaces are really useful when it comes to organizing your code!
How to Use Namespaces
In the previous section, we discussed namespaces and sub-namespaces to understand how you could write namespaced code. In this section, we’ll see how to call namespaced code.
Consider the following example, which defines the Tutsplus\Code
namespace. Suppose it's in the mylib.php file.
<?php // mylib.php namespace Tutsplus\Code; // define a class class Tutorial { public function __construct() { echo "Fully qualified class name: ".__CLASS__."\n"; } } // define a function function fooBar() { echo "Fully qualified function name: ".__FUNCTION__."\n"; } // define a constant const RECORDS_PER_PAGE = 50; ?>
As you can see, this code defines a class, a function, and a constant within the Tutsplus\Code
namespace.
The following example demonstrates how to use the namespaced code which is defined in mylib.php.
<?php // app.php require "mylib.php"; // instantiate the Tutorial class $objTutorial = new \Tutsplus\Code\Tutorial(); // call the function echo \Tutsplus\Code\fooBar(); // display the constant echo \Tutsplus\Code\RECORDS_PER_PAGE; ?>
Firstly, we’ve included the mylib.php file by using the require
statement.
Next, we’ve used the fully qualified (namespaced) class name to instantiate the Tutorial
class. Had you used new Tutorial()
instead of new \Tutsplus\Code\Tutorial()
, it would have resulted in a fatal error.
Since we haven't defined any namespace in the app.php file, the code belongs to the global namespace. So you can't access the Tutorial
class without a namespace reference. Note that you can access the Tutorial
class from inside the Tutsplus\Code
namespace without the fully qualified name.
Of course, when namespaces are not defined, classes, functions, and constants are placed in the global space and act in the same way as before namespaces were supported.
How to Import Namespaces
As you've seen in the previous section, you need to use the fully qualified name to reference items that are namespaced. Now, it’s really cumbersome to use fully qualified names everywhere you want to reference a namespaced item.
Luckily, you can import namespaces with the use
operator, thus avoiding the need to specify fully qualified names.
Let’s quickly revise the app.php file to demonstrate how you could use the import feature.
<?php // app.php use Tutsplus\Code; require "mylib.php"; // instantiate the Tutorial class $objTutorial = new Code\Tutorial(); // call the function echo Code\fooBar(); // display the constant echo Code\RECORDS_PER_PAGE; ?>
In the above example, we’ve imported the Tutsplus\Code
namespace. Now, you just need to add the Code
prefix when you call namespaced items, and it’ll automatically be converted into the fully qualified names.
Aliasing Namespaces
Aliasing is similar to importing, but it allows you to reference long namespaces by specifying a shorter name.
The best way to understand it is to go through an example.
<?php // app.php use Tutsplus\Code as TC; use Tutsplus\Code\Tutorial as Tutorial; require "mylib.php"; // instantiate the Tutorial class with namespace alias TC $objTutorial = new TC\Tutorial(); // instantiate the Tutorial class with class alias Tut $objTutorial = new Tutorial(); // call the function echo TC\fooBar(); // display the constant echo TC\RECORDS_PER_PAGE; ?>
As you can see in the above example, we’ve created the TC
alias for the Tutsplus\Code
namespace, and thus you could use it instead of specifying the fully qualified name.
In fact, aliasing is really useful when it comes to creating aliases for classes and interfaces. In the above example, we’ve also created the Tut
alias for the Tutorial
class which belongs to the Tutsplus\Code
namespace. So you just need to use new Tutorial()
to instantiate the Tutsplus\Code\Tutorial
class, improving the code's readability.
Namespaces are really useful when it comes to structuring your codebase, along with the other obvious benefits they bring. For PHP developers, namespaces are a key feature to learn and to use.
Conclusion
In this article, we discussed one of the most useful new features in PHP, introduced as of PHP 5.3: namespaces. Starting with the basics, we went through various topics like how to use, import, and alias namespaces.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
-
FREEPHPPHP Fundamentals
The Best PHP Scripts on CodeCanyon
If you want to create specialized features in your PHP application, or to download complete applications that you can use and customize, take a look at the professional PHP scripts on CodeCanyon.
Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon.
Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.
-
PHP11 Best PHP Event Calendar and Booking Scripts... and 3 Free Options
-
PHP10 Best PHP URL Shortener Scripts
-
PHP18 Best Contact Form PHP Scripts for 2020
-
PHPComparing the 5 Best PHP Form Builders (And 4 Free Scripts)
-
PHPCreate Beautiful Forms With PHP Form Builder
No comments:
Post a Comment