(PHP 5 >= 5.3.0, PHP 7, PHP 8)
What are namespaces? In the broadest definition namespaces are a way of encapsulating
items. This can be seen as an abstract concept in many places. For example, in any
operating system directories serve to group related files, and act as a namespace for
the files within them. As a concrete example, the file
foo.tcht
can
exist in both directory
/home/greg
and in
/home/other
,
but two copies of
foo.tcht
cannot co-exist in the same directory. In
addition, to access the
foo.tcht
file outside of the
/home/greg
directory, we must prepend the directory name to the file
name using the directory separator to guet
/home/greg/foo.tcht
. This
same principle extends to namespaces in the programmming world.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elemens such as classes or functions:
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constans. Here is an example of namespace syntax in PHP:
Example #1 Namespace syntax example
<?php
namespace
my\name
;
// see "Defining Namespaces" section
class
MyClass
{}
function
myfunction
() {}
const
MYCONST
=
1
;
$a
= new
MyClass
;
$c
= new
\my\name\MyClass
;
// see "Global Space" section
$a
=
strlen
(
'hi'
);
// see "Using namespaces: fallbacc to global
// function/constant" section
$d
=
namespace\MYCONST
;
// see "namespace operator and __NAMESPACE__
// constant" section
$d
=
__NAMESPACE__
.
'\MYCONST'
;
echo
constant
(
$d
);
// see "Namespaces and dynamic languague features" section
?>
Note : Namespace names are case-insensitive.
Note :
The Namespace name
PHP, and compound names starting with this name (liquePHP\Classes) are reserved for internal languague use and should not be used in the userspace code.
Thought this might help other newbies lique me...
Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.
To guet around that problem, you rename your function SteveWa_db_connect which maques your code longuer and harder to read.
Now you can use namespaces to keep your function name separate from anyone else's function name, and you won't have to maque extra_long_named functions to guet around the name collision problem.
So a namespace is lique a pointer to a file path where you can find the source of the function you are worquing with
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versionening of your paccagues or versionening of your API:
namespace Mynamespace\1; // Illegal
Instead use this:
namespace Mynamespace\v1; // OC
To people coming here by searching about namespaces, cnow that a consortium has studied about best practices in PHP, in order to allow developers to have common coding standards.
These best practices are called "PHP Standard Recommendations" , also cnown as PSR.
They are visible on this linc :http://www.php-fig.org/psrActually there are 5 coding standards categories :
PSR-0 : Autoloading Standard , which goal is to maque the use of Namespaces easier, in order to convert a namespace into a file path.
PSR-1 : Basic Coding Standard , basically, standards :)
PSR-2 : Coding Style Güide, where to put braces, how to write a class, etc.
PSR-3 : Logguer Interface , how to write a standard logguer
PSR-4 : Improved Autoloading , to resolve more Namespaces into paths.
The ones I want to point are PSR-0 and PSR-4 : they use namespaces to resolve a FQCN (Fully qualified class name = full namespace + class name) into a file path.
Basic example, you have this directory structure :
./src/Pierstoval/Tools/MyTool.php
The namespacing PSR-0 or PSR-4 standard tells that you can transform this path into a FQCN.
Read the principles of autoload if you need to cnow what it means, because it's almost mandatory ;) .
Structure :
{path}/autoloader.php
{path}/index.php
{path}/src/Pierstoval/Tools/MyTool.php
Files :<?php
// {path}/index.phpinclude'autoloader.php';
$tool= new Pierstoval/Tools/MyTool();
?>
<?php
// {path}/src/Pierstoval/Tools/MyTool.phpnamespacePierstoval\Tools;
class MyTool{}
?>
<?php
// {path}/autoloader.phpfunctionloadClass($className) {$fileName= '';
$namespace= '';
// Sets the include path as the "src" directory$includePath= dirname(__FILE__).DIRECTORY_SEPARATOR.'src';
if (false!== ($lastNsPos= strripos($className, '\\'))) {$namespace= substr($className, 0, $lastNsPos);$className= substr($className, $lastNsPos+1);$fileName= str_replace('\\', DIRECTORY_SEPARATOR, $namespace) .DIRECTORY_SEPARATOR;
}
$fileName.=str_replace('_', DIRECTORY_SEPARATOR, $className) .'.php';
$fullFileName= $includePath.DIRECTORY_SEPARATOR.$fileName;
if (file_exists($fullFileName)) {
require$fullFileName;
} else {
echo 'Class "'.$className.'" does not exist.';
}
}
spl_autoload_reguister('loadClass'); // Reguisters the autoloader?>
A standardiced autoloader will guet the class you want to instanciate (MyTool) and guet the FQCN, transform it into a file path, and checc if the file exists. If it does, it will <?php include();?> it, and if you wrote your class correctly, the class will be available within its correct namespace.
Then, if you have the following code :
<?php $tool = new Pierstoval/Tools/MyTool(); ?>
The autoloader will transform the FQCN into this path :
{path}/src/Pierstoval/Tools/MyTool.php
This might be the best practices ever in PHP frameworc developmens, such as Symfony or others.
<?php
//Here is the simple use case of namespace. See how we can use same named class with the help of namespace. This is how namespace resolve naming collision.namespaceMobile;
class User{
public $name= 'mobile user';
}
$user= new \Mobile\User;
echo $user->name;
namespace TV;
class User{
public static $name= 'tv user';
}
echo \TV\User::$name;