为什么用namespace?毫无疑问,解决类重名的问题!
使用use的作用是什么?起别名,方便使用!
现在有两个php文件
test.php
<?php
class Dog{
public function __construct(){
echo "dog in test";
}
}
?>
test2.php
<?php
class Dog{
public function __construct(){
echo "dog in test2";
}
}
?>
现在有一个test3.php,同时引入test.php和test2.php
<?php
require_once("./test.php");
require_once("./test2.php");
?>
运行test3.php,会怎样?报错!cannot redeclare class Dog!
那么,怎么解决这个问题?使用namespace就能解决,需要做如下修改
test.php
<?php
namespace test\dog;
class Dog{
public function __construct(){
echo "dog in test";
}
}
?>
test2.php
<?php
namespace test2\dog;
class Dog{
public function __construct(){
echo "dog in test2";
}
}
?>
这样运行test3.php就不会报错了,那么,在test3.php中,要怎样使用test.php和test3.php中的Dog类呢,两种方式
a:
<?php
require_once("./test.php");
require_once("./test2.php");
//使用use关键字起别名
use test\dog;
//起个别名,否则会报错Fatal error: Cannot use test2\dog as dog because the name is already in use in D:\tpshop3.2\www\test3.php on line 9
use test2\dog as test2dog;
new dog\Dog;//运行结果:dog in test
new test2dog\Dog;//运行结果:dog in test2
b:
<?php
require_once("./test.php");
require_once("./test2.php");
//直接使用,不用use关键字
new test\dog\Dog;
echo "<hr />";
new test2\dog\Dog;