php new一个类报错,php 命名空间详解

众所周知 命名空间 是php5.3 带来的新特性 可以帮我们解决在工程量大时 类命名重复的问题 下面 我就来分享一下 我对命名空间的理解

首先我们创建三个php文件在同一个文件夹 分别为 index.php test1.php test2.php

test1.php 的内容如下

class test

{

function say()

{

echo 'this is test1 ';

echo "

";

}

}

test2.php 的内容如下

class test

{

function say()

{

echo 'this is test2 ';

echo "

";

}

}

index.php 的内容如下

require_once('test1.php');

require_once('test2.php');

现在当我们调用 index.php 时我们会发现一个错误

daec1eb9ee69850c178521c8ec43923b.png

php提示我们不能声明 test2.php 的 test类

这是为什么呢 其实是因为 test2.php 中的 test类 和 test1.php 中的类重名了 系统不知道该调用哪一个

正是为了解决这一个问题 所以 php5.3 引入了 命名空间这一新特性

现在我们为 test1.php 加上命名空间

namespace space\test1;

class test

{

function say()

{

echo 'this is test1 ';

echo "

";

}

}

同理 test2.php

namespace space\test2;

class test

{

function say()

{

echo 'this is test2 ';

echo "

";

}

}

现在我们在调用 index.php 我们就会发现错误不见了

这是为什么呢 其实是因为 我们加了 namespace 命名空间以后 系统会自动识别 test1.php 的test类 是space\test1里面的 而test2.php 的test类 是space\test2里面的 他们是不同的

下面我们在 index.php 里加上几行代码测试一下

require_once('test1.php');

require_once('test2.php');

$test1 = new \space\test1\test();

$test2 = new \space\test1\test();

$test1->say();

$test2->say();

运行后得到

98d3f100cb31eb488dd1a0a7cb2c15fc.png

我们会发现 运行完美成功

但是每次 初始化 new 一个实例出来的时候 我们都要 写上 $test1 = new \space\test1\test(); 这样的一大长串 是不是有一点不够简洁 正是因为这个原因 php 又为我们 提供了 use 关键字

use 的作用是设定我们默认使用的命名空间

require_once('test1.php');

require_once('test2.php');

use space\test1\test;

$test1 = new test();

$test1->say();

然后 我们在 访问 index.php

9b84933cfca366641dca627df73df309.png

完美 果然 把 test1.php 中的 test类 给实例化出来了

这时候 想必 肯定 会有人 问 那 test2.php 中的 test类 我们怎么实现出来呢

是像下面这样来实现吗

5bea0aec5c69b5b63ff7419669ab937f.png

大家光看照片 就知道 肯定不能 这样来实现了 因为编译器 已经报错了

因为这样的话 系统又会像没有加命名空间一样 不知道该调用哪一个 test类了

为了 解决 这个问题 所以 php 又给我们 推出了 一个 和 use 关键字连用的关键字 as

as的用法是为命名空间取一个别名

require_once('test1.php');

require_once('test2.php');

use space\test1\test;

use space\test2\test as test2;

$test1 = new test();

$test2 = new test2();

$test1->say();

$test2->say();

现在我们在调用 index.php

2a0499984cfeaa1e79e5c810c7e05c89.png

完美运行

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值