Namespacing in PHP

Namespacing in PHP

Tutorial Details
    • Topic: Namespacing in PHP
    • Difficulty: Moderate

It’s been a bumpy ride, in regards to namespace support in PHP. Thankfully, it was added to the language in PHP 5.3, and the applicable structure of PHP code has improved greatly since then. But how exactly do we use them?


What’s a Namespace?

"Don’t forget to escape the backslash when you store a namespace name in a string!"

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. These are your belongings. Directly underneath your drawer is someone else’s, and he puts the same things in it. To avoid using each other’s items, you decide to label the drawers so it’s clear what belongs to whom.

Previously, developers had to use underscores in their classes, functions and constants to separate code bases. That’s equivalent to labeling each others belongings and putting them in one big drawer. Sure, it’s at least some kind of organization, but it’s very inefficient.

Namespacing to the rescue! You can declare the same function, class, interface and constant definitions in separate namespaces without receiving fatal errors. Essentialy, a namespace is nothing more than a hierarchically labeled code block holding regular PHP code.

You are Using Them!

It is important to keep in mind that you indirectly make use of namespaces; as of PHP 5.3, all the definitions which are not yet declared in a user defined namespace fall under the global namespace.

The global namespace also holds all internal PHP definitions, like echo(), mysqli_connect(), and the Exception class. Because the global namespace has no unique identifying name, its most often referred to as the global space.

Note that it’s not an obligation to use namespacing.

Your PHP script will work perfectly fine without them, and this behavior isn’t about to change very soon.


Defining a Namespace

A namespace definition is the first statement the PHP interpreter should encounter in a PHP file. The only statement allowed to occur above a namespace declaration is a declare statement, and then again, only if it declares the encoding of the script.

Declaring a namespace is as simple as using the namespace keyword. A namespace name should obey the same rules as other identifiers in PHP. Therefore, a namespace must start with a letter or underscore, followed by any number of letters, numbers, or underscores.

<?php 
namespace MyProject {
    // Regular PHP code goes here, anything goes!
    function run() 
    {
        echo 'Running from a namespace!';
    }
}

If you want to assign a code block to the global space, you use the namespace keyword without appending a name.

<?php 
namespace {
    // Global space!
}

You are allowed to have multiple namespaces in the same file.

<?php
namespace MyProject {
}

namespace MySecondProject {
}

namespace {
}

You can also scatter the same namespace throughout different files; the process of file inclusion automatically merges them. Therefore, it’s a good coding practice to limit the amount of namespace definitions to one per file, just like you would do with classes.

Namespacing is used to avoid conflicting definitions and introduce more flexibility and organization in your code base.

Note that the brackets surrounding the namespace code block are completely optional. In fact, sticking to the one-namespace-per-file rule and omitting the curly brackets makes your code a lot cleaner–there’s no need to indent the nested code.

Sub-namespaces

Namespaces can follow a certain hierarchy, much like the directories in the file system on your computer. Sub-namespaces are extremely useful for organizing the structure of a project. For example, if your project requires database access, you might want to put all the database-related code, such as a database exception and connection handler, in a sub-namespace called Database.

To maintain flexibility, it is wise to store sub-namespaces in sub-directories. This encourages structuring of your project and makes it much easier to use autoloaders that follow the PSR-0 standard.

PHP uses the backslash as its namespace separator.


Fun fact: in the RFC to decide which namespace separator should be used, they even considered using a smiley.
// myproject/database/connection.php
<?php 
namespace MyProject\Database

class Connection {
    // Handling database connections
}

You can have as many sub-namespaces as you want.

<?php 
namespace MyProject\Blog\Auth\Handler\Social;

class Twitter {
    // Handles Twitter authentification
}

Defining sub-namespaces with nested code blocks is not supported. The following example will throw a very descriptive fatal error: “Namespace declarations cannot be nested”.

<?php
namespace MyProject {
    namespace Database {
        class Connection { }
    }
}

Calling Code from a Namespace

If you want to instantiate a new object, call a function or use a constant from a different namespace, you use the backslash notation. They can be resolved from three different view points:

  • Unqualified name
  • Qualified name
  • Fully qualified name

Unqualified Name

This is the name of a class, function or constant without including a reference to any namespace whatsoever. If you are new to namespacing, this is the view point you are used to working from.

<?php
namespace MyProject;

class MyClass {
    static function static_method()
    {
        echo 'Hello, world!';
    }
}

// Unqualified name, resolves to the namespace you are currently in (MyProject\MyClass)
MyClass:static_method();

Qualified Name

This is how we access the sub-namespace hierarchy; it makes use of the backslash notation.

<?php
namespace MyProject;

require 'myproject/database/connection.php';

// Qualified name, instantiating a class from a sub-namespace of MyProject
$connection = new Database\Connection();

The example below throws a fatal error: “Fatal error: Class ‘MyProject\Database\MyProject\FileAccess\Input’ not found” because MyProject\FileAccess\Input is approached relatively to the namespace you are currently in.

<?php
namespace MyProject\Database;

require 'myproject/fileaccess/input.php';

// Trying to access the MyProject\FileAccess\Input class
$input = new MyProject\FileAccess\Input();

Fully Qualified Name

The unqualified and qualified names are both relative to the namespace you are currently in. They can only be used to access definitions on that level or to dive deeper into the namespace hierarchy.

If you want to access a function, class or constant residing at a higher level in the hierarchy, then you need to use the fully qualified name–an absolute path rather than relative. This boils down to prepending your call with a backslash. This lets PHP know that this call should be resolved from the global space instead of approaching it relatively.

<?php
namespace MyProject\Database;

require 'myproject/fileaccess/input.php';

// Trying to access the MyProject\FileAccess\Input class
// This time it will work because we use the fully qualified name, note the leading backslash
$input = new \MyProject\FileAccess\Input();

It’s not required to use the fully qualified name of internal PHP functions. Calling an unqualified name for a constant or function which does not exist in the namespace you are currently working in results in PHP searching the global namespace for them. This is a built-in fallback which does not apply to unqualified class names.

With this in mind, we can now overload internal PHP functions whilst still being able to call the original function (or constant for that matter).

<?php
namespace MyProject;

var_dump($query); // Overloaded
\var_dump($query); // Internal

// We want to access the global Exception class
// The following will not work because there's no class called Exception in the MyProject\Database namespace and unqualified class names do not have a fallback to global space
// throw new Exception('Query failed!');

// Instead, we use a single backslash to indicate we want to resolve from global space
throw new \Exception('ailed!');

function var_dump() {
    echo 'Overloaded global var_dump()!<br />';
}

Dynamic calls

PHP is a dynamic programming language; so you can also apply this functionality for calling namespaced code. This is essentially the same as instantiating variable classes or including variable files. The namespace separator PHP uses is also a meta character in strings. Don’t forget to escape the backslash when you store a namespace name in a string!

<?php
namespace OtherProject;

$project_name = 'MyProject';
$package_name = 'Database';
$class_name = 'Connection';

// Include a variable file
require strtolower($project_name . '/'. $package_name .  '/' . $class_name) . '.php';

// Name of a variable class in a variable namespace. Note how the backslash is escaped to use it properly
$fully_qualified_name = $project_name . '\\' . $package_name . '\\' . $class_name;

$connection = new $fully_qualified_name();

The namespace Keyword

Not only is the namespace keyword used to define a namespace, it can also be used to explicitly resolve to the current namespace, functionally similar to the self keyword for classes.

<?php
namespace MyProject;

function run() 
{
    echo 'Running from a namespace!';
}

// Resolves to MyProject\run
run();
// Explicitly resolves to MyProject\run
namespace\run();

The __NAMESPACE__ constant

Much like the self keyword cannot be used to determine what the current class name is, the namespace keyword cannot be used to determine what the current namespace is. This is why we have the __NAMESPACE__ constant.

<?php
namespace MyProject\Database;

// 'MyProject\Database'
echo __NAMESPACE__;

This constant is very useful for learning if you are just starting out with namespaces; it is also helpful for debugging. As it is a string, it can also be used in combination with dynamic code calls which we previously discussed.


Aliasing or Importing

"it’s not an obligation to use namespacing"

Namespacing in PHP has support for importing. Importing is also referred to as aliasing. Only classes, interfaces, and namespaces can be aliased or imported.

Importing is a very useful and fundamental aspect of namespacing. It gives you the ability to make use of external code packages, like libraries, without having to worry about conflicting names. Importing is achieved by using the use keyword. Optionally, you can specify a custom alias with the as keyword.

use [name of class, interface or namespace] as [optional_custom_alias]

How it’s Done

A fully qualified name can be aliased to a shorter unqualified name so that you don’t have to write its fully qualified name each time you want to make use of it. Aliasing or importing should occur in the highest scope of a namespace or in the global scope. Trying to do this in the scope of a method or function is invalid syntax.

<?php
namespace OtherProject;

// This holds the MyProject\Database namespace with a Connection class in it
require 'myproject/database/connection.php';

// If we want to access the database connection of MyProject, we need to use its fully qualified name as we're in a different name space
$connection = new \MyProject\Database\Connection();

// Import the Connection class (it works exactly the same with interfaces)
use MyProject\Database\Connection;

// Now this works too! Before the Connection class was aliased PHP would not have found an OtherProject\Connection class
$connection = new Connection();

// Import the MyProject\Database namespace
use MyProject\Database;

$connection = new Database\Connection()

Alternatively, you can alias to it a different name:

<?php
namespace OtherProject;

require 'myproject/database/connection.php';

use MyProject\Database\Connection as MyConnection;

$connection = new MyConnection();

use MyProject\Database as MyDatabase;

$connection = new MyDatabase\Connection();

You are also allowed to import global classes, like the Exception class. When imported, you don’t have to write its fully qualified name anymore.

Note that import names are not resolved as relative to the current namespace but from an absolute standpoint, starting at the global space. This means that a leading backslash is unnecessary and not recommended.

<?php
namespace MyProject;

// Fatal error: Class 'SomeProject\Exception' not found
throw new Exception('An exception!');

// OK!
throw new \Exception('An exception!');

// Import global Exception. 'Exception' is resolved from an absolute standpoint, the leading backslash is unnecessary
use Exception;

// OK!
throw new Exception('An exception!');

Though it is possible to dynamically call namespaced code, dynamic importing is not supported.

<?php
namespace OtherProject;

$parser = 'markdown';

// This is valid PHP
require 'myproject/blog/parser/' . $parser . '.php';

// This is not
use MyProject\Blog\Parser\$parser;

Conclusion

Namespacing is used to avoid conflicting definitions and introduce more flexibility and organization in your code base. Remember that you are not obligated to use namespacing; it’s a feature used in combination with an object oriented workflow. Hopefully, however, you will consider taking your (future) PHP project to the next level by making use of namespacing. Have you decided yet?

Tags: namespace
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://inkwell.dotink.org Matthew J. Sahagian

    The only reason to use namespaces is because, unfortunately, the community won’t take your project too seriously without them. This is sad, since most of the community said “ooohhh new feature, use it!” rather than actually thinking about it and deciding whether or not they made sense in the form which they were presented.

    What’s worse, is most projects use them rather inappropriately with PSR-0 as a way to mimick directory structure. It’s easy to write a few line autoloader that’s PSR-0 compliant and then make your directories match namespaces, however, it really digs into the ridiculousness of PHP namespace issues.

    I don’t agree with all the points, of this article, but it raises some interesting concerns in my opinion:

    http://pornel.net/phpns

    It’s unfortunate, but PHP namespaces were implemented pretty poorly and used even more poorly.

    • http://blog.thomasv.nl ThomasV

      I fully agree with you, just lacked the words to say it in such a way it would sound like logic.

    • thecodingdude

      I agree with you here – I hate PHP namespaces. Syntactically, it’s the worst namespace operator I’ve ever seen.

    • http://samuel.blog.br Samuel Mesquita

      +1 for you comment

      • Jesus Bejarano

        There still room for this club?. I am in.

    • sumyungguy

      It seems every article I read on this site about Php this Matt guy always finds a problem with the article. Php is a fun language but if I had to work with guys like this then I would quit coding and get a job at the closest burger flipping joint. At least that has perks like left over fries and stuff ….meh…

      • http://inkwell.dotink.org Matthew J. Sahagian

        Yes. I’m a developer. I identify and analyze problems, then make them known to stakeholders, and hopefully come up with solutions. That’s what I do.

        PHP is indeed a fun language. A language that I prefer over a great many other languages. That’s precisely why I look for problems in both the language and the community and try to bring them to attention. I’m sure there’s at least something in the world that you are as passionate and caring about as I am about web development.

    • http://www.wimbledon-it.co.uk Richard

      As a redditor I must admit, I assumed it pretty normal that this was the top comment. Then I thought. Hold on a minute, it is pure luck that this good man with this very good comment is on the top. Thank you. Otherwise you got the upvotes ;)

    • http://alexconcepts.com alex

      While I totally agree that namespaces in php aren’t very well implemented (as opposed to C# or Java), people taking from Matt’s comment that they should avoid namespaces altogether is just wrong imo. Namespaces should be used in any OO language.

      Fwiw, I think some of the problems born with php’s namespaces relate to it not being a fully OO language.

    • Alchemication

      Have you considered learning C and diving into the PHP Namespacing source? (if you’re a developer there’s a chance that you already know C…so come on! Show us how to do it right!!!), thanks.
      PS: I hope it’s only the beginning of PHP namespaces and PHP folks will actually implement lot more in the future (but we need to use this feature to encourage them!!!)

      • http://inkwell.dotink.org Matthew J. Sahagian

        Alchemication,

        I know C — I was actually working pretty heavily on the iPodLinux project about 8 years ago — I was 20 then and probably had been doing C for about 4 – 5 years, so while I would feel comfortable working on it I don’t think the problem lies in the technical programming.

        The problem is two-fold.

        1) PHP maintains far too much backwards compatibility between major versions in my book. Frankly, I think PHP 4 should have probably dropped backwards compatibility when they started adding the first OO related stuff in. PHP 5 could have been (while not a full object oriented rewrite, as I think it’s functional nature is nice), at least a chance to add full object oriented fundamental data types.

        2) They simply conceived of namespaces as basically a class prefix. Namespaces don’t have much “feature” to them on their own. They’re not treated as independent segments and certain procedural methods (despite that you can have procedural namespaced functions) are not aware of them except for resolution.

        The fix in my book, or at least a starting point is calling scope namespace resolution.

        I don’t think the problem with this is a “We don’t know how to do it in C problem” — I think the problem with this may be the legacy structure of the rest of the engine as a whole and probably also a matter of wanting to dumb things down.

        That said, it feels pretty weird to me to have to do something like class_exists(__NAMESPACE__ . ‘\Whatever’) – Even weirder if it’s regarding the parent namespace because now I basically have to explode the namespace and pop the end element of the array then recombine it (unless I’m missing some core functionality here).

        All I **really** want is this:

        1) When a class name, constant, function name, etc… is used or passed to a function the current namespace is checked to see if it is valid there.

        2) If not found, the system look at the parent namespace until it is found.

        The only technically difficult thing is the fact that, as far as I know namespaces are resolved at compile time, while something like class_exists() would resolve the string at runtime. This, however, seems like it would be pretty straightforward by tracking the current runtime namespace. These types of things are **obviously** possible since we have late static bindings now.

    • http://evanbyrne.com Evan

      So in nutshell, you don’t use PHP namespaces, because they aren’t as powerful as you would have liked… Flooding the global namespace is the only other solution… Yeeeaaahhh thanks for the suggestion, but no thanks.

      • http://inkwell.dotink.org Matthew J. Sahagian

        All my new projects use PHP namespaces.

        It’s not about whether or not namespaces are “powerful” — it’s about whether or not they’re actually recognized in areas where they should be recognizable.

        The equivalent failure would have been, if when implemented, you couldn’t pass a closure to those methods that support callable arguments.

        i.e. if the following could not work:

        call_user_func(function($name){ echo ‘Hello ‘ . $name; }, ‘World’);

        As far as legacy methods dealing with class names are concerned, the class name is the fully qualified class name, i.e. namespace + class. There is no way to call class_exists() or equivalent with a class name, with respect to the calling namespace.

        There, are, however other major issues as pointed out by the article linked above. Towards the top of that list, in my opinion, is also the fact that namespaces conflict with PHP keywords.

        Flooding the global namespace is not the only other solution. As already mentioned, PHP got away with using psuedo namespaces for *years*. If PHP’s official namespacing had somehow made things less verbose, it’d be a practical win. But it has actually made things more verbose. The entire Flourish library, for example uses a simple lowercase ‘f’ as a namespace. I’d be curious to see if you can find any other non-official-namespaced class out in the wild that exists that would conflict with any one of it’s classes.

        Flourish 2.0 (which I’m working on and aiming to be 5.4+ compatible only) does use namespaces… unfortunately this means lots of crap like this:

        use Dotink\Flourish;

        Flourish\

        __NAMESPACE__ .

        While this may be a win for technical purity… it is not a win for practicality or ease of use.

        The other alternative is, of course, fixing PHP namespaces. This is part sugar and part making the rest of the language more namespace aware.

  • Ashley Clarke

    I understand why we should use namespaces but I think it just looks ugly.

  • http://tisuchi.wordpress.com Thouhedul Islam Suchi

    Hay writer.
    I have read your full article. As far I have understood, it is not much important for PHP developer according to your points. As your description, I think, PHP programmer will avoid namespaces.

  • http://my.opera.com/patkoscsaba/blog/ Patkos Csaba

    Interesting. Nice article.

  • Christian Sciberras

    There are a lot of issues with the article, and some parts of it are outright misleading.

    For instance, `echo()` (which by the way, doesn’t need brackets) is a “language construct”, unlike Exception class or mysqli_whatever(), which are regular classes/functions added by a PHP library.

    The file-scope syntax (`namespace Test;`) is not mentioned in “Defining a Namespace” section, but it is used later on.

    Unlike what’s been said, you can’t avoid the use of namespaces if they are required. If for example you need to create a Database class, but it has already been declared, there no way to redeclare it, unless you use namespacing.

    Now, a little critique about the comments; let me applaud you guys on topping my list of today’s idiots. The way it’s been implemented in PHP makes it natural and well suited with PHP’s syntax. The use of namespacing is to avoid cluttering the main namespace as a tool for organization, not to get a pat in the back from some community. If you can’t see the use of namespacing, I’m sorry to say but you can’t have worked in a real PHP project (and no, 2kloc wordpress plugin is not a big project..).

    • http://inkwell.dotink.org Matthew J. Sahagian

      @ChristianSciberras

      Your example is poor for two reasons.

      1) The conflict that namespaces resolve is on a per project level.

      If you really need to create two classes called `Database` — or if you’re using a third-party class called `Database` and you also have your own class with the same name, I’d wager you’re probably “doing it wrong” for other reasons. At some point, if I had the audience, I wanted to take a poll to understand exactly how frequently namespace conflicts occurred prior to PHP’s namespacing.

      In the 13+ years or so that I’ve been doing PHP, and as a pretty early adopter of OO PHP, I have yet to run into a conflict, prior to namespaces or after. This is because, quite simply, people use varying names and/or fake namespaces.

      Prior to namespaces in PHP, aside from your own developed code, there was probably no class publicly released simply called `Database.` And if there was, chances are it took care of all your database needs and the chance that you’d need to add a conflicting class approached 0 quite rapidly.

      2) You can simply change the name. Assuming limited dependency on the actual implementation, or even a well defined search and replace, you can always simply rename `Database` to something else. Semantic names are great, but I’d wager we actual devalue the semantic meaning of class/project names by encouraging excessive namespaces e.g. Vendor\Project\Helpers\HTML, Vendor\Project\Parsers\HTML, Vendor\Project\Whatever\HTML. Look! 7000 HTML classes, one of which is surely what I need for working with HTML.

      The problem which is better represented above, is the general misuse of namespaces has caused *a lot* of people to take a class called `HTMLParser` and stick it in a namespace called `Parsers` thinking, “Oh, maybe I’ll have other kinds of parsers!” — Great, but now you’re using your namespaces to define functional traits, and, as the article I linked to points out — this can quickly become a problem with PHP’s verbosity in terms of using namespaces.

      I don’t gripe the backslash separator. I actually think it’s quite fitting and OK (ugly or not). My gripe is how **dumb** PHP is when it comes to handling it’s new amazing feature. The article I linked to explains it quite well, so I won’t repeat all those points here.

      The problems in the article are then compounded by the fact that PHP developers truly tie namespaces. “I want all my exceptions stored in the same folder, so obviously I should have a namespace called `Exceptions`.” — NO.

      Speaking of Exceptions: http://onehackoranother.com/logfile/2009/01/php-5-3-exception-gotcha

      Apologizing for having to say that “[we] cannot have worked in a real PHP project” doesn’t really work, because I don’t think anyone here is saying they can’t see the use of namespacing. I think what people here are saying, at least what I’m saying, is that we would love to see namespaces that don’t suck and a community that didn’t so gravely misunderstand their purpose.

      • Me, myself and I

        I will disagree (mostly) today with you.
        Namespacing does solves conflicts; and of course it brings natural organizations of functions (Classes + methods).

        You say that if the other guy has two classes named ‘Database’ then “he is doing it wrong, so he must change the name of the classes”. Seriously? If you do that in your projects when you face such issues then you are the one who is doing it totally wrong – (no offense intended).

        Just for example, if you go to github.com and look for psr-0 compliance libs you will notice that everybody is naturally creating unique FQ namespaces; and if any of them conflicts, it is for sure less common case than for plain old PHP scripts. And having such namespaces makes integrating 3rd party libs into a project quite safe.

        I won’t argue if the php core developers implemented namespaces poorly; but it is a good thing.
        If you find hard to setup an auto-loader + namespacing your classes then that is the reason you don’t like it.

        I will end my commentaries saying that the proof of such value because of namespaces, is a great piece of tool named composer (http://getcomposer.org) that handles dependencies and auto-wiring a piece of cake (and you won’t find a similar robust tool for non-namespaced libs).

        All the best.

      • http://inkwell.dotink.org Matthew J. Sahagian

        @Me, myself and I

        Namespacing has the **potential** to solve conflicts, whether or not it does depends on whether or not conflicts exist.

        The point regarding two `Database` classes is pretty straightforward, and I’m not quite sure you why you find it so hard to understand. The questions that need to be asked are:

        1) What does each `Database` class do?
        2) Do they overlap in terms of functionality?
        3) Do you really plan to use both?

        The argument is simple, it is not that there aren’t two classes in the world with the name Database, it’s that you need to explain why you’re using two classes in the same project named Database. I have never seen a project with two database classes. Such a situation would generally imply there is not a high enough separation of concerns in either, i.e. each offers some fundamental functionality the other does not which is needed, which implies it’s probably more than just one would expect to be in a simple Database class… or that the developer simply doesn’t know what they’re doing.

        The point regarding PSR-0 compliance libs and FQ namespaces is moot. Prior to PHP officially having a mechanism to namespace, namespacing of a sort **still** existed. This is precisely why PSR-0 standardizes converting underscores to directory separators as well as the namespace separator, because we used to have classes with names like `_Database` — hence why the liklihood of two classes with the name `Database` existing was extremely low.

        Having such namespaces does not make integrating 3rd party libraries into a project any more or less “safe” — it’s not a question of safety. It’s a question of how much work is involved. If the practical number of occurrences of conflicts was previously 0, then it is no more or less safe.

        If you’re not arguing the implementation, then why are you arguing with me at all? My entire point is that namespaces are implemented poorly, not that they are not useful in some way or even desirable regardless of practical need.

        There is nothing hard about setting up a PSR-0 autoloader. There’s plenty stupid there though. My auto-loader is quite fine and there was nothing difficult about writing it. But my autoloader actually support multiple standards so I can map patterns to different directories and transformation patterns. For example, I create a static mapping of ‘PSR0: vendor’ — that is, attempt to load using the PSR-0 standard from vendor. This is because, unfortunately, a large minority of the community now is pushing this ridiculous “standard” and the majority of the community simply has no other agreed practice. But why on Earth would I want to use PSR-0?

        The pattern I use is quite different, and in my mind, a bit more sane. For one, it promotes flatter namespaces. Additionally it keeps with my lower/underscore directory structure, for example, a controller such as “UsersController” might be found in ‘/controllers/dotink/inkwell/authentication’ as opposed to ‘/vendor/Dotink/Inkwell/Authentication/Controllers’. You’re welcome to choose that hot mess if you like, but I’m quite happy avoiding it.

        Composer could easily exist for non namespaced classes. There’s nothing inherent in namespaces that makes composer possible. PEAR, while not as rich, did quite fine without official namespaces using the _ separator. Again, why do you think PSR-0 requires you to convert underscores as well?

        Your arguments here have little to do with PHP namespaces and much more to do with namespacing in general, which I don’t take issue with. My issue is with how PHP does namespaces and how the community equates them to directory structure.

      • http://blog.techwheels.net Nikunj Bhatt

        @Matthew J. Sahagian

        I read the whole article and also all your comments, I am really agree with you. But not completely to the reply to Christian Sciberras regarding having 2 database classes.

        However there is much little possibility to use 2 database classes but a need could arise when the 2 database classes are dealing with 2 different DBMS. For example, one class is used to connect with MySQL and another is used to connect with PostgreSQL; and/or where these 2 DBMS are at different locations, one is at localhost while the other is at a remote server.

        No offense, this just a real example where namespace can be used. I also mostly prefer NOT to use it at all the time, it should only be used when it is actually required. I also hate when people use Joomla or WordPress for a 5-10 pages’ static website!

      • Christian Sciberras

        Matthew, sorry for my rather late reply, I know I should waste more time with the internet society…or whatever it is.

        My example is only poor from a particular perspective – yours. If you read between the lines, you’ll see why it is not and what my point is. Anyway, let me try it again, replying to your comments instead.

        1) Sure, conflicts, may be per project, but consider class Database conflicts in lib A and lib B of project AA, while class Controller conflicts with lib B and lib C of project BB. Happens you used the same library B which has conflicts in two different projects. Sure, per project basis – two of them. Solution? Drop lib B and hope for an alternative.

        In your 13 years of experience, I suppose you must have used some form of framework? Now what if your favourite framework had a class conflict with that of a library? Another framework? Sure, you can always do MyAwesomeFrameworkSomeClass and SomeOtherLibrarySomeClass. I just hope you never need to get a list of classes. Hey, you’d even be better of with a text editor for code here…

        2) Sure, I just open up wordpress and rename get_page() to wp_get_page(), easy!
        Back to my example code, I’m sure that we only need one database class – it’s only 12 or so different methods, you can’t miss any feature you might need, right?

        When I think about your namespace-less naming scheme, I tend to feel a little sick in the stomach. I mean, “Controllers_Dotink_Inkwell_Authentication”, really?? And you can’t see anything wrong with that?

        The point behind namespacing is NOT to have an excessive path/structure, but even the fact that you can offload all of the wordpress/joomla/whatever core inside a namespace called wordpress makes it something. Do you **really** need get_page() inside the PHP scope?

        On the other hand, when you’re writing a wordpress template, does it really have to use wordpress_get_page(), wordpress_get_current_user()… (wp_ is too generic!)

        Finally, the “but we were better before and it worked” crap…. sure, I used to write batch scripts for websites, and it worked. Dynamic HTML content? No problems, just an iframe to frame_news.php. Some fine days they were…

      • http://twitter.com/judge99 Jason Judge

        Matthew,
        Just picking up on one point about namespace clashes prior to PHP namespacing: not it did not happen a lot. It did not happen anything like *enough*. There just was not enough portable library and package use to make it a problem, because so much code was rewritten and ported for each specific project. Now with namespacing, whole communities of reusable and portable libraries are popping up. And that is great. It feels like PHP has turned a corner.

    • http://blog.thomasv.nl ThomasV

      And who are you to judge for everyone and call them “idiots”. All people have their own opinion on such subjects and may or may not choose to agree with others too. But insulting them and stating that the have never worked on a “real” PHP project before is telling others that your opinion means everything like you rule the world or something.

      And let me return your implication with an implication of my own: you probably have never worked with real people before because the way you lack respect to other peoples judgement is disturbing. And real (and big) PHP projects are not done by one self, but by a team of people who think alike and don’t think alike. Respecting other people will work in any project, calling people idiots doesn’t.

      -1 for your comment, if that wasn’t obvious yet.

      Good day.

      • Christian Sciberras

        Thomas, if you don’t want to be judged, do not put your ignorance on display by sharing it with the rest of the world. :)

        Saying things like “I don’t personally see any point to namespacing” is an opinion, for instance. Saying “it is fact that namespacing is completely useless, doesn’t solve anything and only implies you’re a bad coder”, on the other hand, is not opinion. Who’s the other guy to call people beginners just because they have different requirements?

        For the record, I currently head a team of at least three different developers with an iron fist, but I don’t consider any one of them an idiot. If I did, s/he wouldn’t be there in the first place.
        See, expressing clueless comments about something you don’t understand isn’t something I tolerate. I personally think people should be called by whatever abilities they display, just as I expect anyone else would to my personality. Again, if you don’t like the attitude, you’re not fit for the internets :)

  • http://www.opwernby.com Dan Sutton

    So, then, yet again they’ve done something which works in opposition to the syntax of the rest of the language: namely, letting a backslash be used. I also hate the fact that the global namespace is simply unnamed.

    When is PHP going to become a language in which every command isn’t an exception to the way every other command works? It’s such a horrible, ill-conceived abortion of a nightmare of a pretend language.

    • http://alexconcepts.com alex

      I totally agree with your point. And the reason it is “such a horrible, ill-conceived abortion of a nightmare of a pretend language” I think is because it was first a procedural language and OO capability was later added to it (“on top of it” would better state my point).

      The way things should have happened (or even should happen at some point, but it might be to late) is that php should become fully OO. I wouldn’t have a problem, for backwards compatibility’s sake, to have to write something like “using OOPHP;” at the beginning of every file, which should contain exclusive OO code.

    • http://www.diigital.com Mike

      wait, so was the nightmare aborted, or was the abortion ill-conceived and the nightmare survived?

      • Sam

        +1

  • Sarfraz Ahmed

    Simply great article on php namespacing, this one makes it all easy to understand now. Thanks

  • Boabramah Ernest

    I think the issue of the namespace has been debated a lot. I believe that before it was implemented not every everyone supported it. If you love it use it and do not use it if you don’t. At the end of the day, it is the application you build that count.

  • CasualBystander

    @Matthew J. Sahagian

    A single thought popped into my head after reading your comments here and this quote from your site:

    “Over the past two years it has grown into a stable and robust framework which abandons the cargo-cult mentality of existing MVC and HMVC frameworks, favoring configurability and developer accessibility over hyped up design and development patterns.”

    NIHS: http://en.wikipedia.org/wiki/Not_invented_here

    • http://inkwell.dotink.org Matthew J. Sahagian

      @CasualBystander

      A single thought popped into my head after reading a number of comments here.

      SM: http://en.wikipedia.org/wiki/Straw_man

      As you *should* be able to clearly see from my posts, I’m more than willing to debate the actual issues. I write lengthy responses to address very specific points made by other people in most of my comments. Rather than address my points in their subsequent responses, they prefer to distract from them completely.

      i.e. claiming that I’m somehow saying namespacing is a bad idea as opposed to what I’m actually saying, that namespacing is implemented poorly by both the language and the community and giving examples.

      From your article:

      “The reasons for not wanting to use the work of others are varied, but can include fear through lack of understanding, an unwillingness to value the work of others, or forming part of a wider “turf war.”"

      - Fear through lack of understanding

      I would imagine the technical detail of my posts refutes this quite plainly. Admittedly, it is true that I lack the understanding of why the PHP community does some of the ridiculous things that it does.

      - An unwillingness to value the work of others

      My framework (since you brought it up), is moreso comprised of the work of others than it is my own. Admittedly, it is true that I don’t value the work of others who may be technically inept or confused.

      - Forming part of a wider “turf war”

      Admittedly, I don’t think PHP should be trying so hard to be Java (or at least if it and the community are going to do so, stop failing so miserably).

      • CasualBystander

        I do not agree with your argument viewing PSR-0 compliance with namespaces, in which you find it a moot point. Naming collision is just one of the benefits of having namespaces in PHP. You also gain the ability to import/alias. Being able
        to alias classes, interfaces, and even namespaces themselves is a great feature. Look at where annotation driven mechanisms are going (such as Doctrine with @ORM\Column, etc.)

        This is an example of how you would “namespace” prior to actually having namespaces:

        ========================================

        class Vendor_Bundle_InvoiceBundle_Entity_Invoice_LineItem
        {
        public function addDiscount(Vendor_Bundle_AccountingBundle_Entity_Definition_DiscountInterface $discount)
        {
        return $this->discounts->add($discount);
        }
        }

        ========================================

        note, you have now directly tied every method in not only this class that needs to interact with DiscountInterface, but also every other class within your app that does the same. Sure you can do a mass search/replace, but regardless ugly is ugly.

        The following snippet takes advantage of namespace and alias. Much easier to read? yes. A single line to update if we ever need to change interface? yes.

        ========================================

        namespace Vendor\Bundle\InvoiceBundle\Bundle\Entity\Invoice;

        use Vendor\Bundle\AccountingBundle\Entity\Definition\DiscountInterface as Discount;

        class LineItem
        {
        public function addDiscount(Discount $discount)
        {
        return $this->discounts->add($discount);
        }
        }

        ========================================

        In regards to the scenario of having two classes of the same name, you mentioned that you have never seen an application with two “Database” classes. Have you seen more than one class in a single application of a different name?

        Here is an example of a perfectly reasonable real world scenario:

        Vendor\Bundle\AccountingBundle\Entity\Discount
        Vendor\Bundle\InvoiceBundle\Entity\Discount

        The first is an entity for allowing an admin to define a product discount, be it percentage or flat. The latter is a recorded discount stored in an invoice. They surely have the same name, but I also surely do not want to reference them as such everywhere they are interacted with:

        Vendor_Bundle_AccountingBundle_Entity_Discount
        Vendor_Bundle_InvoiceBundle_Entity_Discount

        I can go on and on with scenarios.

        You also mentioned that PHP should stop trying to be like Java or stop failing at trying to be like Java. Do you work with Java? It is a very verbose language. You seem to strongly dislike having to reference a class ONE time by its FQN, but you prefer to write a basterdly long class name EVERYWHERE in a file (assuming you are type hinting…). Would you really rather be -just- like java?

        Should we have to do something similar to this in PHP to just instantiate an array?

        Import java.util.HashMap.
        HashMap someMap = new HashMap();

        Heaven forbid importing other libraries like:

        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.PathVariable;

        zomg! it’s just like having to “use” a namespace in PHP, only it has a “.” instead.
        Are there some things that could be improved on? Surely. But the fact is, the benefits are proven to outweigh the costs of not using them at all just because you see yourself as a purist refusing to accept their benefits if it doesn’t live up to what you expect. It’s also foolish to lead any new PHP developers not to use them because of the “issues” you have stated.

      • CasualBystander

        Ah, it removed some bits of the code. Hopefully this works.

        Import java.util.HashMap.
        HashMap someMap = new HashMap();

      • casualBystander

        No luck with the as stated below the comment box -_-

        Import java.util.HashMap.
        HashMap<String, String> someMap = new HashMap<String, String>();

      • http://inkwell.dotink.org Matthew J. Sahagian

        @CasualBystander

        You do not “gain the ability to import/alias blah blah blah” — Importing is a necessary feature of namespacing, without namespacing the question of importing would be meaningless. With regards to aliasing, there is nothing that would prevent class aliasing without namespacing — indeed, it would likely function EXACTLY the same.

        Again, using older Flourish as an example, there would be nothing to prevent class_alias() from existing independent of namespacing and allowing something like the following:

        use fDatabase as Database;

        or explicitly:

        class_alias(‘fDatabase’, ‘Database’);

        Your examples are pure hyperbole. The entire “standard” of Vendor/Package not to mention the excessive subnamespaces are a symptom of PHP’s adoption of namespacing, they are, again, not inherent in its use or lack thereof. There is nothing that prevents you from having a class called ‘AccountingDiscount’ and ‘InvoiceDiscount’ and I would challenge you to show me where such class names would conflict with any other class you know of on the planet.

        What you do to instantiate a class comes down to syntactic sugar really. Javascript has no problem instantiating objects for fundamental data types.

        var whatever = ‘string’;

        whatever.split(…);

        The only reason PHP refuses to do such a thing is due to backwards compatibility.

        Lastly, there is nothing foolish about pointing out the pitfalls of PHP namespaces, especially to new developers. If anything it might help them to resolve issues when using them which might otherwise be confusing, such as the case with Exceptions as pointed out in another comment and the case of reserved keywords being used in namespaces.

        Namespaces solve only a single issue practically — AVOIDING CONFLICTS. The question is then simply, how common were conflicts? Whether or not namespaces were a much needed feature boils down to that.

        Whether or not they are implemented in such a way that is ideal is another question altogether. Perhaps you would like to illustrate the usefulness of importing namespaces when using the likes of interface_exists(), class_exists(), class_alias(), method_exists(), property_exists(), etc, as it relates to verbosity. Or how about centrally defining constants in subnamespaces? etc.

      • CasualBystander

        The comparison with Java package namespaces are not hyperbole. They are real, and used everyday. Is this an ok namespace in your opinion?

        use Vendor\Web\Bind\Annotation\RequestMethod;

        as compared to java:

        import org.springframework.web.bind.annotation.RequestMethod;

        The topic of AccountingDiscount and InvoiceDiscount, the example was simplified for brevity.

        Consider:

        /Accounting
        AccountingFlatDiscount
        AccountingPercentDiscount
        AccountingDiscountRuleInterface
        AccountingDiscountRuleAbstract
        AccountingDiscountRuleHasProduct
        AccountingDiscountRuleHasProductQuantity
        AccountingDiscountRuleHasProductOption

        …. and on and on….

        InvoiceDiscount

        vs:

        /Accounting
        /Discount
        FlatRate
        Percent

        /Rule
        /Definition
        DiscountRuleInterface
        DiscountRuleAbstract
        HasProduct
        HasProductQuantity
        HasProductOption
        …..

        Does the old way of having crazy long class names prevent collision? Most likely. But you end up sacrificing readability to simply give PHP namespaces and the PSR-0 the cold shoulder.
        In my personal opinion, this is much more legible.

      • http://inkwell.dotink.org Matthew J. Sahagian

        @CasualBystander

        I think you’re missing the point with regards to Java.

        Java allows for the following:

        import java.swing.*;

        You’re also missing the greater point, which is that something like C++ allows for the following:

        namespace foo {

        class FooBar {

        }

        namespace bar {
        FooBar *fb;
        }
        }

        In short… every other language that implements namespacing has some sort of understanding of namespaces as actual contexts. PHP does not. Namespacing in PHP is purely about aliasing/prefixing.

      • CasualBystander

        Java:

        import java.swing.*;

        PHP:

        use java\swing;

        Both cases bring the sub namespaces into context for direct usage.

      • http://inkwell.dotink.org Matthew J. Sahagian

        @CasualBystander

        Except it doesn’t. PHP doesn’t import anything, it merely aliases.

      • CasualBystander

        Aliased or not, its still within context for use.

        You just have to reference Swing\Something();

        not the end of the world at all.

    • CasualBystander

      What is wrong with having to access the library as:

      $something = new Swing\Something();

      ?

      You can’t even alias in Java. If a naming collision occurs you have to reference the FQN of the secondary class.

  • http://www.tricktodesign.com tricktodesign

    From a long time i was trying to understand the concept of php namespaces. But it was of no use. The way you tell it is quite easy from to understand it. Really nicely written (With example). Thanks a Lot for sharing…

  • phpcoder

    This is a great unnecessary complexity in your project. I agree on some thoughts here, think twice before implementing everything they offer.. this is especially an issue when you use a lot of libraries don’t having namespaces or you have existing project which works perfectly (and does exactly what it should) fine without any ns or other fancy technologies (btw i actually love packages in Java, but ns in PHP is a different story)..

  • http://jamesontodder.webstarts.com/ Kevyn May

    We are confirmed by you that namespace allowed in PHP Web development.and we came to know all the details and codding of namespace in PHP by your sites.

  • http://www.elimcmakin.com Eli McMakin

    Excellent article. Would love to see more articles on basic PHP on this site.

  • http://brianscaturro.com brian

    I personally think namespaces are a benefit. However, the mentioned headaches they present in PHP are pretty obvious.

    The mention of mixing libraries following PSR-0 and those that do not does make things a little messier. Composer does a great job of exposing it’s autoloader so you can mangle things if necessary.

    Overall, I am a fan – but it certainly deviates from the way we have traditionally done things in PHP.

  • sarabjeet

    I really like that you are giving information on PHP MYSql .Being enrolled at http://www.wiziq.com/course/5871-php-mysql-with-basic-javascript-integrated-course i found your information very helpful indeed. Thanks for it.

  • http://vernonaustin.weebly.com/ Owen Walsh

    Namespacing is used to prevent inconsistent explanations and present more versatility and company in your value platform. Keep in mind that you are not required to use namespacing; it’s a function used along with an item focused work-flow. Hopefully, however, you will consider getting your PHP venture to the next stage by using namespacing.

  • Amador Cuenca

    Nice tutorial. Thanks.

  • Amkosys

    Nice one !! Can you post one more tuts to explain difference between Classes and Namespace? In which case need to use namesapce? and classes? That will be very good help

    Thanks

  • http://www.matthewsetter.com/ Matthew Setter

    Namespaces are a great addition to the language, despite the bubbling controversy. Like any feature though, they shouldn’t be used “just because you can”; but when it’s practical and beneficial to do so. Love the fun fact about the smiley!

  • http://www.facebook.com/shahnawaz.rules Shahnawaz Rules

    nice tutorial..