定义子命名空间

(PHP 5 >= 5.3.0, PHP 7)

与目录和文件的关系很象,PHP 命名空间也允许指定层次化的命名空间的名称。因此,命名空间的名字可以使用分层次的方式定义:

Example #1 声明分层次的单个命名空间

<?php
namespace MyProject\Sub\Level;

const 
CONNECT_OK 1;
class 
Connection /* ... */ }
function 
connect() { /* ... */  }

?>
上面的例子创建了常量MyProject\Sub\Level\CONNECT_OK,类 MyProject\Sub\Level\Connection和函数 MyProject\Sub\Level\connect

add a note

User Contributed Notes 5 notes

up
15
dak at pvpallday dot com
5 months ago
He was saying you cannot use '/' or '.' in the Namespace names.

Only '\'.
up
27
do dot not dot reply at foxmail dot com
1 year ago
treat sub-namespaces as different namespace

a.php:
<?php namespace ABC;
const
'__DOMAIN__' = 'example.com';
?>

b.php
<?php namespace ABC\SUBLEVEL;
require
'a.php';
echo
__DOMAIN__; //Notice: Use of undefined constant __DOMAIN__
up
38
leaksin [ at ] gmail [ dot ] com
2 years ago
Never use slashes and dot in namespace declaration.

wrong formats:

<?php

namespace first\second.w;

?>

<?php

namespace first/second;

?>
up
-1
maycon dot rodrigues1 at gmail dot com
2 months ago
The calling to a function, class or constant in the current code file can be:

<?php
namespace MyTest;

const
TEST = 777;

//in this way
echo \MyTest\TEST;

//Or this way
echo TEST// is the same "\MyTest\TEST".

You must notice others behavior for youself .
up
-143
steve dot pye at gmail dot com
1 year ago
Wait a minute. So the document says to declare it like:

namespace Something\SomethingElse;

and you're saying "never do that"? what the what?