一、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
随时随地看视频