264
votes

What are PHP Namespaces?

What are Namespaces in general?

A Layman answer with an example would be great.

11

11 Answers

604
votes

Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.

In simple terms, think of a namespace as a person's surname. If there are two people named "John" you can use their surnames to tell them apart.

The Scenario

Suppose you write an application that uses a function named output(). Your output() function takes all of the HTML code on your page and sends it to the user.

Later on your application gets bigger and you want to add new features. You add a library that allows you to generate RSS feeds. This library also uses a function named output() to output the final feed.

When you call output(), how does PHP know whether to use your output() function or the RSS library's output() function? It doesn't. Unless you're using namespaces.

Example

How do we solve having two output() functions? Simple. We stick each output() function in its own namespace.

That would look something like this:

namespace MyProject;

function output() {
    # Output HTML page
    echo 'HTML!';
}

namespace RSSLibrary;

function output(){
    # Output RSS feed
    echo 'RSS!';
}

Later when we want to use the different functions, we'd use:

\MyProject\output();
\RSSLibrary\output();

Or we can declare that we're in one of the namespaces and then we can just call that namespace's output():

namespace MyProject;

output(); # Output HTML page
\RSSLibrary\output();

No Namespaces?

If we didn't have namespaces we'd have to (potentially) change a lot of code any time we added a library, or come up with tedious prefixes to make our function names unique. With namespaces, we can avoid the headache of naming collisions when mixing third-party code with our own projects.

21
votes

A namespace allows you to place a bunch of code under a name and not have any naming conflicts with classes, functions and constants.

It allows your code to live in that namespace.

PHP uses the somewhat controversial character \ to show namespace levels. People got up in arms because it is also used as an escape character.

To use the namespace in PHP, use something like this at the top of your file.

namespace my\namespace;

You can find a lot more information on the official PHP documentation for namespaces.

12
votes

Since it’s easier to learn about the keyword “use” by knowing about “namespace”, let me explain namespace first by looking at a basic Laravel project.

There is a controller class with the name: Controller.php which is in the path: app/Http/Controllers from the project’s root directory There is also another controller class named: Controller.php, but this one is in the path: vendor/laravel/framework/src/Illuminate/Routing from the project’s root directory

You don’t need to look at the source code yet if you’re new to php because it can confuse you, instead let me explain to you the part of it that we care about and will help us understand “namespace” and “use”.

So as a matter of fact, our first controller class: app/Http/Controllers/Controller.php needs to use the Second controller class vendor/laravel/framework/src/Illuminate/Routing/Controller.php. it actually needs to extend this Class in order to have access to its content for handling some crucial routing functionalities.

So how can a class extend another class that has the same name? class Controller extends Controller? this will NOT work, unless there is a way to distinguish these two classes and that’s where namespace comes handy and the use keyword helps to complete the mission of, allowing the usage of; (classes; methods; interfaces and constants), with the same name, in the same scope.

now how is it done in the code? very simple! if we look at app/Http/Controllers/Controller.php source code, we can see at the top of the class namespace is declared as: namespace App\Http\Controllers, so this is how you give your class a namespace so it can be referenced by other classes now this looks the same as the path to this class from the project’s root directory, with little difference and that’s the usage of “\” instead of “/(same as command prompt in windows), but there is another difference and that’s the App with capital ‘A’ in the namespace versus ‘app’ with Lowercase ‘a’ in the path. Also note that namespace is case-sensitive.

So namespace is a separate concept than the path, it can follow the path structure if it helps but it doesn’t have to be exact path to the class, method, interfaces or constants for example take a look at: vendor/laravel/framework/src/Illuminate/Routing/Controller.php source code,

we see at the top of the class the namespace is declared as: Illuminate\Routing

now let’s take look at the “use” keyword, we use, the “use” keyword to make our class aware of a specific class or function that we want to use in our class

so we are not importing or including anything we’re just letting our class know that we will be using a specific class or method by referencing them by their namespace let’s take a look at app/Http/Controllers/Controller.php source code, as you can see from the line: “use Illuminate\Routing\Controller as BaseController”, the “use” keyword followed by namespace for the target class (note that Illuminate\Routing\Controller.php and Illuminate\Routing\Controller ‘without .php extension’ are interchangeable)

we can use the “as” keyword along with the “use” keyword to give a specific class, method, interfaces or constants an alias which allows app/Http/Controllers/Controller.php to extend Illuminate\Routing\Controller.php as BaseController in the line: “class Controller extends BaseController”.

9
votes

There are techniques like namespaces in other programming languages (like packages in Java). They are used to be able to have mutliple classes with the same name wihtin a project.

From the php documentation (http://www.php.net/manual/en/language.namespaces.rationale.php):

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

4
votes

A Namespace works like a directory. You know how you can put files in a directory with the same names as files in the parent (or any other) directory? Well, a namespace lets you do that within an application for variables, functions and classes.

There was a bit of a trend in PHP a little while ago for huge classes of static functions. The only way to call any of those functions was by prefixing a call with the class name. This was a primitive attempt at namespaces, but with not very much of the benefits.

4
votes

Much like directories and files, namespace in PHP serves to group classes, functions, interfaces and constants.

Example:

Filesystem      |   PHP Namespace
----------------|------------------
/Dir/File.txt   |  \Namespace\Class

It provides a way of wrapping items from the global space and allows use of plain item name without causing name collision in a program. It's supported in PHP 5.3.0, PHP 7.

But there are some limits in analogy between PHP namespace and Unix based filesystem:

                          | Filesystem            |        PHP Namespace
--------------------------|-----------------------|-------------------------
Cas sensitive             |       No              |        Yes                
--------------------------|-----------------------|-------------------------
Name with plain number    |       Yes             |        No
--------------------------|-----------------------|-------------------------
Path level                |       Yes             |        Yes   
--------------------------|-----------------------|-------------------------
Plain metacharacters name |       Yes             |        No        

The principle extends to namespace in programming word.

3
votes

Namespace is like packaging many things into a single pack. Imagine a namespace as a drawer in which you can put all kinds of things: a pencil, a ruler, a piece of paper and so forth. To avoid using each other's items, you decide to label the drawers so it's clear what belongs to whom.

2
votes

A namespace basically lets you put code into a container. This will prevent problems with two functions (as well as classes and variables) that share the same name.

These are useful when working when larger applications to prevent issues with pieces of code sharing the same name.

For example, lets say we wanted two functions called "TheMessage" . These both would print (echo) different messages each. Normally, this would cause a syntax error, as you cannot have two functions that share the same name.

To fix this, you could put these functions into separate namespaces. This would allow you to use both functions without any errors.

0
votes

A namespace is a simple system to control the names in a program.
It ensures that names are unique and won’t lead to any conflict.

0
votes

You can use namespace to avoid name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants. Namespaces also have the ability to alias (or shorten) Extra_Long_Names designed to reduce the first problem, improving readability of source code.

As we all know, namespaces and traits are not new in PHP, but still many php developers don’t use these Great concepts because of their complexity. So, in this post. I’ll try to clear them with examples. What are namespace and traits?

How you can implement them in your code to make your code reusable and extensible?

Benefits of namespaces

You can use namespace to avoid name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

Namespaces also have the ability to alias (or shorten) Extra_Long_Names designed to reduce the first problem, improving readability of source code. Let’s understand namespaces with an example. create a folder name “php_oops” in htdocs(xampp) or www (xwamp) create a new folder under root directory named “namespaces”, & then create a file index.php under namespaces folder.

<?php
// FilePath:- namespaces/index.php

// let's say, we have two classes in index,
// here, these two classes have global space
class A 
{ 
   function __construct()
   { 
      echo "I am at Global space, Class A";
   }
}
class B
{
   function __construct()
   {
      echo "I am at Global space, Class B";
   }
}
// now create an object of class and 
$object = new A; // unqualified class name
echo "<br/>";
$object = new \B; // fully qualified class name
// output: 
I am at Global space, Class A
I am at Global space, Class B

Reference- https://medium.com/@akgarg007/php-laravel-namespaces-and-traits-01-9540fe2969cb

-1
votes

Namespace is used to enclosed group of codes so that they can be used in different places without name conflicts. Think about this as jQuery no conflict method and you will understand it better.