1.

What is a namespace?

Answer»

Namespaces are a way of encapsulating items. In the PHP world, namespaces are designed to solve two problems that AUTHORS of libraries and applications encounter when creating reusable code elements such as classes or functions:

  1.    Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2.    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, interfaces, functions and constants.

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

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();


Discussion

No Comment Found