php命名空间

xiaoxiao2021-02-28  29

PHP 命名空间(namespace)是在PHP 5.3中加入的,如果你学过C#和Java,那命名空间就不算什么新事物。 不过在PHP当中还是有着相当重要的意义。

PHP 命名空间可以解决以下两类问题:

用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性。

对于我们初学者来说,我们使用命名空间一般都是为了解决类名字冲突的问题,即若出现名字相同的类,则可以放在不同的命名空间中来区分它们。接下来直接通过例子来解释吧。

先创建两个文件:a.php,b.php

<?php //a.php namespace a; class Test { public function hello() { echo "hello a "; } }

<?php //b.php namespace b; class Test { public function hello() { echo "hello b "; } }

a.php和b.php分别定义了一个名字相同的Test类,通过输出不同的内容来区分他们。

若把两个命名空间写在一个文件中,则是这样的写法:

namespace a{ class Test{ public function hello() { echo "hello a "; } } } namespace b{ class Test{ public function hello() { echo "hello b "; } } }

以下的情景都是两个命名空间分别写在a.php和b.php中

接下来创建test.php,用来在网页中打印测试结果。

1.$test = new a\Test() ;//空间名\类名()直接实例化对象

<?php //test.php require_once( 'a.php'); require_once( 'b.php'); //将a.php和b.php包含进来,此时test.php中就有了a和b两个命名空间 $test = new a\ Test(); //实例化对象 $test-> hello(); //调用hello()函数输出信息

输出结果:hello a

<?php //test.php require_once( 'a.php'); require_once( 'b.php'); //将a.php和b.php包含进来,此时test.php中就有了a和b两个命名空间 $test = new b\ Test(); //实例化对象 $test-> hello(); //调用hello()函数输出信息

输出结果:hello b

2.use a\Test;//use关键字

<?php //test.php require_once( 'a.php'); require_once( 'b.php'); $test1 = new a\ Test(); $test2 = new a\ Test(); $test3 = new a\ Test();

若遇到这样需要实例化多个对象,则会比较麻烦,这时我们就需要use关键字默认使用某个命名空间来简化

<?php //test.php require_once( 'a.php'); require_once( 'b.php'); use a\ Test; $test1 = new Test(); $test2 = new Test(); $test3 = new Test(); $test1-> hello(); $test2-> hello(); $test3-> hello();

输出结果:hello a hello a hello a

3.use b\Test as BTest;

在上面情景中若想继续使用命名空间b中的Test类,可以给它重新起个名字,操作如下

<?php //test.php require_once( 'a.php'); require_once( 'b.php'); use a\ Test; use b\ Test as BTest; $test1 = new Test(); $test2 = new BTest(); $test1-> hello(); $test2-> hello();

输出结果:hello a hello b

4.$test = new \Test();//全局类

接下来我们再创建一个c.php

<?php //c.php class Test{ public function hello() { echo "hello c "; } }

其中Test类没有存放在命名空间中,或者说它存在一个顶层的命名空间中,这样的称它为全局类。

要想在之前的情景中使用c.php中的Test类,操作也很简单,在Test()前加一个\就可以了。

<?php //test.php require_once( 'a.php'); require_once( 'b.php'); require_once( 'c.php'); use a\ Test; use b\ Test as BTest; $test1 = new Test(); $test2 = new BTest(); $test3 = new \ Test(); $test1-> hello(); $test2-> hello(); $test3-> hello();

输出结果:hello a hello b hello c

参考资料:

https://www.imooc.com/video/7834

http://www.runoob.com/php/php-namespace.html

转载请注明原文地址: https://www.6miu.com/read-1950174.html

最新回复(0)