Php, namespaces overview

Namespaces overview

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.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, functions and constants. Here is an example of namespace syntax in PHP:

Coomment:

Anonymous 14-Jul-2011 11:14
PHP Namespaces do not only provide a way in which to group related classes, functions and constants, but also a way in which to group related classes, interfaces, functions and constants.

Dmitry Snytkine 31-May-2011 01:54
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:

Namespace Mynamespace1; // Illegal
Instead use this:
Namespace Mynamespacev1; // OK

SteveWa 27-Feb-2011 04:45
Thought this might help other newbies like me…

Name collisions means:
You create a function named db_connect, and somebody elses code that you use in your file (i. e. an include) has the same function with the same name.

To get around that problem, you rename your function SteveWa_db_connect which makes your code longer and harder to read.

Now you can use namespaces to keep your function name separate from anyone else’s function name, and you won’t have to make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with



Php, namespaces overview