Namespace & use

The purpose of namespacing is to avoid clashing class names in different packages or libraries. In PHP before version 5.3, clashing class names was always a possible issue you had to account for. With namespacing, clashing class names is a relic PITA of the past. You should also think of namespacing as an internal directory structure within PHP (and not the file system, which is what threw me for a loop learning about namespaces).

The purpose of the use statement is to import classes from outside packages into your own package or application. The other feature of use, as you noted, is to alias the class name.

Things also start to make even more sense, as is in pretty much all cases when using Symfony, when we have an autoloader running the show for “requiring” the files needed to load classes. When we have an autoloader, your first example would look like this.

namespace index;

use Foobar\Bar as Foo;

print(Foo::foo());

The require isn’t necessary with an autoloader. And, you would usually alias the class and not the namespace.

With PHP7, we can even consolidate the use class importing, if all the classes come from the same namespace.

//current usage of use.
use FooLibrary\Bar\Baz\ClassA;
use FooLibrary\Bar\Baz\ClassB;
use FooLibrary\Bar\Baz\ClassC;
use FooLibrary\Bar\Baz\ClassD as Fizbo;
// new usage of use in PHP7.

use FooLibrary\Bar\Baz\{ ClassA, ClassB, ClassC, ClassD as Fizbo };

If you are a fan of Game of Thrones, then you might like this blog post and explanation of namespaces.

Scott