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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短