Namespace Declaration


 

Namespace Declaration

In this tutorial we will study about namespace declaration in PHP, how to declare namespace in PHP, how to access etc. Examples will make this clearer.

In this tutorial we will study about namespace declaration in PHP, how to declare namespace in PHP, how to access etc. Examples will make this clearer.

Namespace Declaration:

The term namespace is very much common in OOP based language, basically it is a collection of classes, objects and functions. Namespaces are one of the new feature in PHP 5.3.0. Naming collision of classes, functions and variables can be avoided.

We can put any code of PHP within a namespace, but in general class, functions, and constants are placed for easy identification and retrieval. 

A namespace is declared with namespace keyword, but we should keep remember that namespace is introduced in PHP 5.3.0 and if we try this in older version of PHP then a error message would appear. The namespace should always declare on the top of the page.

In PHP, namespaces are used to solve two problems:

  1. Name confliction between  user developed code and internal PHP or any other third party code of classes/functions/constants

  2. With the help of namespace we can get rid of long names, and it is designed to get the ease or relive from the first problem.

Example:

<?php

namespace mySpace;

function myFunction()

{

echo __FUNCTION__;

}

class One

{

function myMethod()

{

echo __METHOD__;

}

}

$obj=new One;

$obj->myMethod();

?>

 

Output:

0

mySpace\One::myMethod

Ads