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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便