php的命名空间是为了管理类,防止类名冲突。后面添加的路径为了方便查找。
第一个命名空间前不能有任何代码。
1.php
class Person{
function __construct(){
echo 'I am one!'."<br>";
}
}
2.php
<?php
require_once '1.php';
new Person();
new \Person();
输出
I am one!
I am one!
没有namespace相当于类在 '/' 之下。
若是1.php加
namespace one;
则name.php 加
new one\Person();
因为类在 '\one'之下了,而不在 '\'之下。 若是name.php也有namespace test ,则默认是在 'teset\onw\' 之下。
use的用法:
namespace animal\dog;
class Life{
function __construct(){
echo 'dog life!'."<br>";
}
}
namespace animal\cat;
class Life{
function __construct(){
echo 'cat life!'."<br>";
}
}
new Life(); // cat life!
new \animal\dog\Life(); // dog life!
use animal\dog; // 若是没有这一行 则下一行报错'animal\cat\dog\Life' ,use相当于选择目录一样。
new dog\Life(); // dog life!
use animal\dog as d; // 也可以是类名 相当于给类起别名 animal\dog\Life as dog new d();
new d\Life();
当有好几行的use的时,表示将要使用这几个命名空间,备选这几个命名空间。new的时候始终是默认当前的命名空间,所以use不能说相当于切换,只能说相当于备选目录。
namespace animal\yao\dog; class Fe{ function __construct(){ echo 'dog life!'."<br>"; } } namespace animal\jiao\cat; class Life{ function __construct(){ echo 'cat life!'."<br>"; } } namespace animal\jiao\pig; class Life{ function __construct(){ echo 'pig life!'."<br>"; } }
namespace mine\me; require_once '1.php'; //不包含则找不到1.php中的命名空间 use animal\yao\dog\Fe; use animal\jiao\cat; use animal\jiao\pig; new Fe(); new cat\Life(); new pig\Life(); class bb { function __construct() { echo 'hhhh'."<br>"; } } new bb();
输出:
dog life!
cat life!
pig life!
hhhh