php之namespace浅析

为什么用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;

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值