PHP Namespace
In PHP Namespace are a way of encapsulating items, for example, any operating system directories serve to related files.
Such a file 'foo.txt' exist in both directory '/home/data1/foo.txt' and '/home/data2/foo.txt'.
But two copies of 'foo.txt' can not co-exist in the same directory.
To access 'foo.txt' together from outside of its directory. We prepend the file name with a directory separator.
Understand PHP namespace in the programming world
You have two pages that contain same Classes names, Function names and Constant names but every page Classe, Function and Constant are different from other page's Classes, Functions and Constant.
Learn from this example:
File1
demo-namespace-1.php
<?php
namespace file1;
class MyClass {
function Hello() {
echo "Hello Class 1";
}
}
function DEE() {
echo "Hello my function 1";
}
?>
Hint: - Declare namespace before including any file.
File2
demo-namespace-2.php
<?php
namespace file2;
include('demo-namespace-1.php');
class MyClass {
function Hello() {
echo "hello class 2";
}
}
function DEE() {
echo "Hello my function 2";
}
echo \file1\MyClass::Hello() . '<br/>';
echo \file1\DEE() . '<br/>';
echo '<br/>';
echo \file2\MyClass::Hello() . '<br/>';
echo \file2\DEE() . '<br/>';
/* If you call Class or Function without namespace, this will print */
echo '<br/><br/>';
echo MyClass::Hello() . '<br/>';
echo DEE() . '<br/>';
?>
Defining multiple namespaces
(1) You can define multiple namespaces in the same file.
(2) You can define different Classes and Functions with the same names.
Understand from this example
<?php
namespace PHP;
class MyClass {
function Dic() {
echo "This is PHP class";
}
}
function MyFunction() {
echo "This is PHP function";
}
namespace PYTHON;
class MyClass {
function Dic() {
echo "This is Python class";
}
}
function MyFunction() {
echo "This is Python function";
}
namespace JAVA;
class MyClass {
function Dic() {
echo "This is Java class";
}
}
function MyFunction() {
echo "This is Java function";
}
/* Output with namespace */
echo \PHP\MyClass::Dic() . '<br/>';
echo \PHP\MyFunction() . '<br/><br/>';
echo \PYTHON\MyClass::Dic() . '<br/>';
echo \PYTHON\MyFunction() . '<br/><br/>';
echo \JAVA\MyClass::Dic() . '<br/>';
echo \JAVA\MyFunction() . '<br/><br/>';
?>