PHP namespace – do you really know all of it?

PHP namespace – do you really know all of it?

PHP namespace is a new concept to many beginners in PHP. I know that because it was a bit confusing and new for me too, when I started learning PHP.

So, I thought, let’s have a very intuitive and detailed learning about this namespace stuff.

Where can I get this namespace thing quickly?

Even though the above heading is very impressive, you really wouldn’t want to leave this article yet. Would you?

Just kidding! If you are a professional in coding and just need the syntax, usage guide and examples in short; you could head straight to the PHP namespace documentation and figure it out yourself.

However, for beginners, I would suggest strictly; stick to this article to get a very good understanding.

What is PHP namespace – where to start?

PHP namespace is more like a combination of the encapsulation and abstraction concept. As you know, PHP is an object oriented programming language and thus uses all the concepts of OOP.

Encapsulation is the concept wherein a group of attributes and behavior for similar behaving entities are packed into one single unit. This enables ease of access, proper classification and implementing proper access limitations.

Abstraction is the level of access that is applied to entities or their encapsulations.

php namespace definition and understanding all syntax

So, PHP namespace can be well compared to the JAVA package concept.

A PHP namespace is used when we want to group together classes or objects that have similar functionalities or belong to the same working methodology.

So, we can say that when we require to create a bundle of classes and objects that are created for a specific purpose or specific functionality, we may declare them under the same PHP namespace.

Declaring such common entities under one single PHP namespace has some vital advantages –

  1. Level of abstraction can be controlled; level of access.
  2. Naming convention is eased out.

So, now when you’re accessing with the help of a PHP namespace, you need not worry whether your provided name (for a class, function or constant) has a clash with any system or library classes; or even classes from some other project.

How to use a PHP namespace?

Using a PHP namespace is pretty easy.

Creating a namespace

NOTE: Just after the PHP tag, you should mention your PHP namespace name, inside your file. No other code or keyword comes before the namespace keyword, not even extra whitespace (except the declare keyword).

See the below code from PHP.NET

namespace MyProject; // fatal error - namespace must be the first statement in the script

Once you have specified this keyword, all methods, classes, interfaces and constants you declare; are becoming part of this namespace or encapsulation.

See the below example –

namespace A100WebSolutions;

const BOOL = 1;
class Example { /* ... */ }
function method1() { /* ... */ }


You can create a directory like structure also while using a PHP namespace.

Just like you write directory paths, write in the same manner while defining a namespace. See the below code from PHP.NET

namespace MyProject\Sub\Level;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }


So, in the above example, the const would be created as MyProject\Sub\Level\CONNECT_OK and class would be created as MyProject\Sub\Level\Connection and so on.

How can I declare multiple PHP namespace in the same PHP file?

This is not recommended by PHP, however, it is achievable. PHP recommends separating out multiple namespaces in different files.

The syntax that allows this is keeping individual namespace contents in curly braces.

See the below code from PHP.NET where global namespace contents and custom namespace contents are being declared in the same file

namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace { // global code
$a = MyProject\connect();
echo MyProject\Connection::start();

Declaring Aliases and shortening namespace paths using only sub-namespace names

Aliases can be used to shorten namespace names to one words. This is only for ease of use.

For example, the following code –

use A100WebSolutions\Example\Test as Something
// Now Something can be used in place of A100WebSolutions\Example\Test while accessing members.

Also, if we declare sub-namespaces with the keyword “use”, PHP considers an automatic alias creation where the whole path is automatically hooked to the lowest sub-namespace.

See the below code –

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

Accessing Namespace members

PHP namespace can be accessed by –

  1. Either the use of the __NAMESPACE__ magic constant. This outputs a STRING and must be concatenated with the namespace member name. It is kind of dynamic access.
  2. Or by using the namespace keyword. This does not form a STRING, rather is a type of static access and always returns the current namespace fully qualified path.

Have a look at the below code to understand all the concepts that I have mentioned –

namespace A100WebSolutions\exampleNS; // Namespace declaration with a sub-namespace
use A100WebSolutions\exampleNS as Something;  //Creating an Alias

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;                     
// In the above, PHP will try to call constructor of Global Scope Class MyClass (if it exists) 
$c = new Something\MyClass; // USing Alias

$c = new \A100WebSolutions\exampleNS\MyClass;
// In the above, PHP will try to call constructor of the class MyClass mentioned in namespace A100WebSolutions\exampleNS 

$d = namespace\MYCONST;        
// In the above, the value of A100WebSolutions\exampleNS\MYCONST is assigned to the $d variable.
// So, echo constant($d) will not work here and throw error. As it will not be able to find
// a value for the expression---- echo constant(1);
echo $d;        

$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); 
// In the above, the $d variable now contains a String value containing the fully qualified namespace path.
// So, echo constant($d) will work here and display the result for
// the expression---- echo constant(\A100WebSolutions\exampleNS\MYCONST);


Do not forget these while using a PHP namespace

  1. Never start a PHP namespace name with a number. PHP does not allow that. It must always start with a letter and then maybe followed by a number.
  2. Namespaces cannot contain the keywords PHP or php. This is reserved by the language itself.
  3. PHP namespace only affects classes, interfaces, functions and constants.
  4. The namespace keyword must not be preceded even by extra whitespace.
  5. While defining any constants under a namespace using the method DEFINE, the namespace must be specified while making a call to the system method “DEFINE”. See the code below –
/* By default, PHP considers all define method to use the GLOBAL namespace (/). So when write DEFINE(‘MESSAGE’, ‘HELLO WORLD’);
It becomes as constant MESSAGE under the GLOBAL SCOPE – 
/* The below code is from PHP.NET official documentation */
namespace test;
define('MESSAGE', 'Hello world!');

The following code will define two constants in the “test” namespace.

namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
  1. While accessing PHP namespace elements using a full qualified path, remember to precede the namespace names with a “\”. This shows that the namespace is under the GLOBAL namespace. Otherwise, it will hit an error.

Comments are closed.