一、namespace
what is namespace
namespace,命名空间,是为了解决项目多人协同开发,类重名冲突的问题。
两个重名的Class导入同一文件的例子:
// Allan.phpclass Cat { public function intro() { echo 'i am cat of Allan'; } }// Tom.phpclass Cat { public function intro() { echo 'i am cat of Tom'; } }// ------------------------// test.phprequire Allan.phprequire Tom.php (new Cat())->intro();// 那这个Cat到底是哪个Cat
为了解决上面的问题,namespace出现了。
How to use
把类分配到它的命名空间下面,以便区分两个类,和正常使用:
// Allan.phpnamespace allan\animal;class Cat { public function intro() { echo 'i am cat of Allan'; } }// Tomnamespace tom\animal;class Cat { public function intro() { echo 'i am cat of Tom'; } }// ------------------------// test.php(new allan\animal\Cat())->intro(); (new tom\animal\Cat())->intro();
二、use
试想有以下场景:
namespace allan\app\class\animal\cat;class Tiger { public function intro() { echo 'i am super cat'; } }// ------------------------// test.php$cat = new allan\app\class\animal\cat\Cat(); $cat->intro();
命名空间太长,也不方便代码阅读。这时候,可以使用use,为上面的例子Tiger,起个别名。
在使用Tiger文件中,也就是test.php:
// test.phpuse allan\app\class\animal\cat\Cat as SuperCat;// 起别名$cat = new SuperCat(); $cat->intro();
三、总结
namespace:解决类命名重复,也可以说是类前缀
use:为名字太长的namespace,起个小名( ̄ ̄)"
作者:夏镇冰茶
链接:https://www.jianshu.com/p/a885262304e1
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦