在同一个文件中定义多个命名空间
也可以在同一个文件中定义多个命名空间。
<?php
namespace Foo;
class Baz
{
//
}
/**
* Return the name of the current namespace.
*
* @param void
* @return string
*/
function baz(): string
{
return __NAMESPACE__;
}
const BAZ = __NAMESPACE__;
namespace Bar;
class Baz
{
//
}
/**
* Return the name of the current namespace.
*
* @param void
* @return string
*/
function baz(): string
{
return __NAMESPACE__;
}
const BAZ = __NAMESPACE__;
不建议使用这种语法在单个文件中定义多个命名空间。建议使用下面的大括号形式的语法。在实际的编程实践中,非常不提倡在同一个文件中定义多个命名空间。这种方式的主要用于将多个 PHP 脚本合并在同一个文件中。
<?php
namespace Foo
{
class Baz
{
//
}
/**
* Return the name of the current namespace.
*
* @param void
* @return string
*/
function baz(): string
{
return __NAMESPACE__;
}
const BAZ = __NAMESPACE__;
}
namespace Bar
{
class Baz
{
//
}
/**
* Return the name of the current namespace.
*
* @param void
* @return string
*/
function baz(): string
{
return __NAMESPACE__;
}
const BAZ = __NAMESPACE__;
}
将全局的非命名空间中的代码与命名空间中的代码组合在一起,只能使用大括号形式的语法。全局代码必须用一个不带名称的 namespace
语句加上大括号括起来。
<?php
namespace Foo
{
class Bar
{
//
}
/**
* Return the name of the current namespace.
*
* @param void
* @return string
*/
function bar(): string
{
return __NAMESPACE__;
}
const BAR = __NAMESPACE__;
}
namespace
{
var_dump(new Foo\Bar()); // object(Foo\Bar)#1 (0) { }
var_dump(Foo\bar()); // string(3) "Foo"
var_dump(Foo\BAR); // string(3) "Foo"
}