批改状态:合格
老师批语:
用大括号语法实现一个脚本中创建多个命名空间并访问成员:
namespace One{
const NAME = 'peter';
class Db
{
public static function demo()
{
return __METHOD__;
}
}
function hello()
{
return '欢迎学习php';
}
//访问Two成员
echo hello().'<hr>';
echo \Two\hello().'<hr>'; //Two的hello
print_r(NAME);
}
namespace Two\Three{
const NAME = '我是Two\Three定义的常量';
}
namespace Two{
const NAME = '朱老师';
class Db
{
public static function demo()
{
return __METHOD__;
}
}
function hello()
{
return '欢迎来php中文网学习php';
}
// echo __NAMESPACE__.'12'; 打印命名空间
echo NAME,'<hr>'; //1.非限定名称: 类似于当前文件
echo Three\NAME; //2.限定名称: 使用命名空间前缀(相对于相对路径)
echo \One\NAME.'<hr>'; //3.完全限定名称: 从根空间/完全限定空间开始找(相当于绝对路径)
echo '当前的命名空间是:'.__NAMESPACE__.'<hr>';
echo namespace\Db::demo();
echo namespace\Three\NAME;
}2.use导入类,并使用别名访问
<?php
namespace test1;
require '9.6test2.php';
//use test2\Test2; //导入类,并且类的别名默认就是test2
//use test2\Test1 as Testnew; //如果导入的类名和当前类中的类名冲突,需要 'as' 关键字起个别名
use test2\test3\test4 as hello; //导入类名空间的别名
class Test1
{
public static function demo()
{
return __METHOD__;
}
}
echo Test1::demo().'<hr>';
echo hello\Test1::demo();3.限定,非限定,完全限定的命名空间之间的区别与联系
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号