关于命名空间

  先写两个文件

a.php

1 <?php
2 class apple {
3     function get_info() {
4         echo "this is A apple";
5     }
6 }

b.php

1 <?php
2 class apple {
3     function get_info() {
4         echo "this is A apple";
5     }
6 }

然后我在index.php中引用这两个文件

1 <?php
2 require_once('a.php');
3 require_once('b.php');
4 
5 $apple = new apple();
6 $apple->get_info();

因为a.php和b.php都包含了class apple这个类,index.php调用apple这个类的时候就会出现问题:

1 Fatal error: Cannot redeclare class apple in D:phpStudyWWW
amespace.php on line 3

这时候就需要使用到namespace了,在a.php和b.php分别加上namespace

a.php

1 <?php
2 namespace ac;
3 class apple {
4     function get_info() {
5         echo "this is A apple";
6     }
7 }

b.php

1 namespace def;
2 class apple{
3      function get_info() {
4         echo "this is B apple";
5     }
6 }

然后在index.php中调用时(使用use表示使用该命名空间中的apple)

1 <?php
2 require_once('a.php');
3 require_once('b.php');
4 
5 use acapple;
6 
7 $apple = new apple();
8 $apple->get_info();

这时浏览器输出:

1 this is A apple

如果我们使用两个use呢?

 1 <?php
 2 require_once('a.php');
 3 require_once('b.php');
 4 
 5 use acapple;
 6 use defapple ;
 7 
 8 $apple = new apple();
 9 $apple->get_info();
10 
11 echo "<br>";
12 
13 $bapple = new apple();
14 $bapple->get_info();

浏览器输出:

Fatal error: Cannot use defapple as apple because the name is already in use in D:phpStudyWWW
amespaceindex.php on line 6

也就是在引用apple这个类的时候,有两个apple,虽然是申明了命名空间,但引用的时候就不知道到底使用的是哪个,

这时就需要使用别名了(使用as来命名别名);

 1 <?php
 2 require_once('a.php');
 3 require_once('b.php');
 4 
 5 use acapple;
 6 use defapple as Bapple ;
 7 
 8 $apple = new apple();
 9 $apple->get_info();
10 
11 echo "<br>";
12 
13 $bapple = new Bapple();
14 $bapple->get_info();

浏览器输出:

this is A apple
this is B apple

这时我们新建c.php,并且不给命名空间

1 <?php
2 class apple{
3     function get_info(){
4         echo "this is c apple";
5     }
6 }

然后在index.php中:

 1 <?php
 2 require_once('a.php');
 3 require_once('b.php');
 4 require_once('c.php');
 5 
 6 use acapple;
 7 use defapple as Bapple ;
 8 
 9 $apple = new apple();
10 $apple->get_info();
11 
12 echo "<br>";
13 
14 $bapple = new Bapple();
15 $bapple->get_info();
16 
17 echo "<br>";
18 
19 $capple = new apple();
20 $capple->get_info();

直接在$capple引用c.php中的apple时,前面加上符号即可,表示全局类。

输出:

this is A apple
this is B apple
this is c apple
原文地址:https://www.cnblogs.com/jacson/p/namespace.html