namespace命名空间

namespace解决命名冲突问题

a.php

1
2
3
4
5
6
7
8
9
<?php

// namespace a\b\c;

class Apple{
function get_info(){
echo 'this is A';
}
}

b.php

1
2
3
4
5
6
7
8
<?php
// namespace a\b\d;

class Apple{
function get_info(){
echo 'this is B';
}
}

index.php

1
2
3
<?php
include('a.php');
include('b.php');

访问index.php时会报错

当加上namepase时, 就不会报错

当实例化对象时 也要加上命名空间

1
2
$a = new a\b\c\Apple();
$a->get_info();


可以加上use a\b\c\Apple
以后实例化就不用加上前面的重复代码了

1
2
3
4
5
6
7
8
use a\b\c\Apple;
$a = new Apple();
$a2 = new Apple();
$a3 = new Apple();

$a->get_info();
$a2->get_info();
$a3->get_info();


如果我们想实例化B.php里面的Apple时

1
2
3
$b = new a\b\d\Apple();

$b->get_info();


但是如果我们多次使用时也会造成 重复多余
如果加上use a\b\d\Apple;
会与use a\b\c\Apple 产生冲突 ,于是利用取别名

1
2
3
4
5
6
7
use a\b\c\Apple;
use a\b\d\Apple as BApple;
// $a = new Apple();

$b = new BApple();

$b->get_info();

当有个c.php

1
2
3
4
5
6
7
<?php

class Apple{
function get_info(){
echo 'this is C';
}
}

当在index.php调用c.php中的Apple
此为全局顶层类,要想对全局顶层类进行实例化 需要在实例化加上反斜杠

1
2
3
4
5
6
7
8
9
10
11
<?php
include('a.php');
include('b.php');
include('c.php');
use a\b\c\Apple;
use a\b\d\Apple as BApple;

$b = new BApple();

$c = new \Apple();
$c->get_info();