Professional Documents
Culture Documents
Name Spaces
Name Spaces
A namespace is a container which allows us to put the relevant classes, functions, objects etc
Naming collision of classes, functions and variables can be avoided. As per the rule of namespace we cannot assign same name to more than one class /function/ or namespace. 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.
A namespace definition is the first statement the PHP interpreter should encounter in a PHP file The only statement allowed to occur above a namespace declaration is a declare statement A namespace name should obey the same rules as other identifiers in PHP A namespace must start with a letter or underscore, followed by any number of letters, numbers, or underscores
Calling Namespace
In a file named lib1.php, we will define a constant, a function, and a class within the AppLib1 namespace: Lib1.php <?php namespace mySpace; function myFunction() { echo __FUNCTION__; } class One { function myMethod() { echo __METHOD__; }
Lib2.php <?php header('content-type:text/plain'); include('Lib1.php'); echo mySpace\myFunction()."\n"; echo mySpace\One::myMethod(); ?> Output: mySpace\myFunction mySpace\One::myMethod
Multiple Namespace In a single PHP file we can declare more than one namespace. It is strongly discouraged to combine multiple namespaces into the same file. No coding should write outside the namespace brackets except the declare statement Example: <?php namespace mySpace; function myFunction() { echo __FUNCTION__;
class One { function myMethod() { echo __METHOD__; } } namespace newspace; class Two { function secondMethod() { echo __METHOD__; } } ?>
Sub Namespace
This technique helps us to achieve more manageability Example: <?php namespace mySpace\FirstLevel\SecondLevel; function myFunction() { echo __FUNCTION__; } class One { function myMethod() { echo __METHOD__; } } echo mySpace\FirstLevel\SecondLevel \myFunction()."\n"; echo mySpace\FirstLevel\SecondLevel \One::myMethod(); ?>