PHP 使用命名空间
phpserver side programmingprogramming更新于 2025/8/19 21:07:17
简介
命名空间中的类、函数或常量可以通过以下方式使用:
- 使用当前命名空间中的类
- 指定相对于当前命名空间的命名空间
- 提供命名空间的完全限定名称
从当前命名空间加载
在此示例中,从 test1.php 加载命名空间。未使用命名空间引用的函数或类名将访问当前命名空间中的函数或类名
示例
#test1.php
<?php
namespace myspace\space1;
const MAX = 100;
function hello() {echo "hello in space1
";}
class myclass{
static function hellomethod() {echo "hello in space1
";}
}
?>
在以下代码中使用此文件
示例
<?php
namespace myspace;
include 'test1.php';
const MAX = 200;
function hello() {echo "hello in myspace
";}
class myclass{
static function hellomethod() {echo "hello in myspace
";}
}
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
";}
class myclass{
static function hellomethod() {echo "hello in myspace
";}
}
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
";}
class myclass{
static function hellomethod() {echo "hello in myspace
";}
}
\myspace\hello();
\myspace\space1\hello();
\myspace\myclass::hellomethod();
\myspace\space1\myclass::hellomethod();
echo \myspace\MAX . "
";
echo \myspace\space1\MAX;
?>
输出
以上代码显示以下输出
hello in myspace hello in space1 hello in myspace hello in space1 200 100

