您的位置:首页 > 编程语言 > PHP开发

PHP中使用命名空间

2017-12-26 11:05 471 查看
为什么要使用命名空间

1.用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突

2.为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。

- - - 摘自php手册

(以下测试 , 命名比较乱 , 希望不影响你的心情 , 哈哈)

Example#1

<?php
namespace Test\Test\One;
class example
{
function __construct(){
echo 'test';
}
}

new \Test\Test\One\example();
// new test1();
//命名空间不区分大小写
new \TEST\TEST\ONE\example();


这两方式都可以调用

Example#2

namespace.php
<?php
namespace Test\Test\One;
class Example
{
function __construct(){
echo 'test';
}
}

new \Test\Test\One\Example();
// new test1();
//命名空间不区分大小写
new \TEST\TEST\ONE\Example();

namespace1.php
<?php

define('NAME','huang');
const AGE= 2;
function test()
{
echo '根下的方法';

4000
}
class Examples{

function fun(){

echo 'examples的fun方法';
}
}
namespace2.php
<?Php

namespace Test;

include "./namespace.php";
include './namespace1.php';
//要是没有命名空间的话 , 两个相同的类名肯定会报错的
class Example
{
function __construct()
{
echo 'test1';
}
}

new Test\One\Example();//调用namespace.php下的example方法
new \Test\Test\One\Example();
new Example();//调用当前空间下的类
new \Test\Example();//调用当前

//默认情况下使用函数,类,常量,会在当前的命名空间下查找
test();
echo AGE;
echo NAME;
//类不会在根空间找,只在当前空间下找 , 没有就拉倒
$obj = new Examples();
$obj->fun();


接下来介绍use

use 相当于给命名空间起了个别名 , 像Linux下alias给那些常用并且又很长的命令起别名

Example#3

<?php
namespace haha\haha\test;
use haha\haha\test as t;

function demo()
{
echo 'demo';
}

t\demo();
demo();
\haha\haha\test\demo();


Example#4
<?php

namespace haha\haha\test;
use haha\haha\test;
function demo()
{
echo 'demo';
}

test\demo();
//如果use的时候不加as,name默认使用子命名空间下的最后一个作为别名


Example#5

use.php
<?php

namespace My\God\Test;
require('./use1.php');
use My\Goden\demo;

$a = new demo;
$a->ha();

use1.php
<?php
namespace My\Goden;

class demo
{
function ha()
{
echo 'use默认最后一个路径可以作为引入的类名,方法和常量则不可以';
}
}


Example#5
use2.php
<?php
namespace haha\haha\test;

function demo()
{
echo 'demo';
}

use3.php
<?php

namespace test\test\test;
use test\test\test as tt;
include('./use2.php');
use haha\haha\test as t;

function demo()
{
echo 'haha';
}
t\demo();

tt\demo();

//导入的文件可以使用命名空间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: