PHP使用名称空间
介绍
命名空间中的类,函数或常量可以通过以下方式使用:
在当前命名空间中使用类
指定相对于当前命名空间的命名空间
提供命名空间的全限定名称
从当前命名空间
在此示例中,从test1.php加载了命名空间。没有命名空间引用的函数或类名称将访问当前命名空间中的功能或类名称
示例
#test1.php
<?php
namespace myspace\space1;
const MAX = 100;
function hello() {echo "hello in space1\n";}
class myclass{
static function hellomethod() {echo "hello in space1\n";}
}
?>在以下代码中使用此文件
示例
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
static function hellomethod() {echo "hello in myspace\n";}
}
hello();
myclass::hellomethod();
echo MAX;
?>输出结果
hello in myspace hello in myspace 200
使用相对命名空间
在下面的示例中,函数和类使用相对命名空间
示例
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
static function hellomethod() {echo "hello in myspace\n";}
}
space1\hello();
space1\myclass::hellomethod();
echo space1\MAX;
?>输出结果
上面的代码显示以下输出
hello in space1 hello in space1 100
完全合格的命名空间
函数和类被赋予绝对命名空间名称
示例
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace\n";}
class myclass{
static function hellomethod() {echo "hello in myspace\n";}
}
\myspace\hello();
\myspace\space1\hello();
\myspace\myclass::hellomethod();
\myspace\space1\myclass::hellomethod();
echo \myspace\MAX . "\n";
echo \myspace\space1\MAX;
?>输出结果
上面的代码显示以下输出
hello in myspace hello in space1 hello in myspace hello in space1 200 100