네임스페이스 개요

(PHP 5 >= 5.3.0, PHP 7)

네임스페이스란 무엇일까요? 넓은 의미로 볼 때 네임스페이스는 내용을 캡슐화 하는 방법중 하나입니다. 이것은 다양한 관점에서 추상적인 개념으로 볼 수 있습니다. 예를 들면 운영체제에서 디렉토리는 관련된 파일들의 그룹을 담당하고, 그 안에 있는 파일들의 네임스페이스 역할을 합니다. 구체적인 예로, 파일 foo.txt는 디렉토리/home/greg/home/other에 각각 존재 할 수 있습니다. 하지만, foo.txt라는 두개의 사본은 동일한 디렉토리에 동시에 존재할 수는 없습니다. 게다가 /home/greg 디렉토리 바깥에서 foo.txt 파일에 접근하려면, 디렉토리 구분자와 함께 파일 이름 앞에 디렉토리 이름을 붙여서 /home/greg/foo.txt 처럼 접근해야 합니다. 이와 같은 원칙은 프로그래밍 세계에서 네임스페이스로 확장됩니다.

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:

  1. Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2. Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. 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: fallback 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 language features" section
?>

Note:

Namespace names PHP and php, and compound names starting with these names (like PHP\Classes) are reserved for internal language use and should not be used in the userspace code.

add a note add a note

User Contributed Notes 4 notes

up
877
SteveWa
13 years ago
Thought this might help other newbies like 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 get around that problem, you rename your function SteveWa_db_connect  which makes your code longer 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 make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with
up
290
Dmitry Snytkine
13 years ago
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 versioning of your packages or versioning of your API:

namespace Mynamespace\1;  // Illegal
Instead use this:
namespace Mynamespace\v1; // OK
up
176
pierstoval at gmail dot com
10 years ago
To people coming here by searching about namespaces, know 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 known as PSR.

They are visible on this link : http://www.php-fig.org/psr

Actually there are 5 coding standards categories :
PSR-0 : Autoloading Standard , which goal is to make 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 Guide, where to put braces, how to write a class, etc.
PSR-3 : Logger Interface , how to write a standard logger
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 know 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.php
   
include 'autoloader.php';
   
$tool = new Pierstoval/Tools/MyTool();
?>

<?php
   
// {path}/src/Pierstoval/Tools/MyTool.php
   
namespace Pierstoval\Tools;
    class
MyTool {}
?>

<?php
   
// {path}/autoloader.php
   
function loadClass($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_register('loadClass'); // Registers the autoloader
?>

A standardized autoloader will get the class you want to instanciate (MyTool) and get the FQCN, transform it into a file path, and check 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 framework developments, such as Symfony or others.
up
24
shewa12kpi at gmail dot com
3 years ago
<?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.

namespace Mobile;

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;
To Top