它上去既像类又像接口,但其实都不是。
trait可以看做类的部分实现,可以混入一个或多个现有的php类中,其作用有两个:表明类可以做什么;提供模块化实现。trait是一种代码复用技术,为php的单继承限制提供了一套灵活的代码复用机制。
2、php版本要求:
php5.4开始引入trait,其目的就是在于减少代码的重复,增加代码的复用性。
3、trait的使用场景:
试想这样一种情况,当有一个方法需要在很多的类中使用时,该怎么处理?
通常一般的处理方式会是,写一个基础类,在基类中实现这个方法,然后所有类都继承这个基类。
这是一种处理方法,但不是最好的处理方式。通常采用继承的情况是:几个类具有很大的相似性。比如人作为一个基类,学生、工人、等继承“人”这个基类来扩展。
由此,trait的作用就出来了,trait 可以在多个类中使用。
4、trait如何使用:
引用php手册中的例子:
例子一
<?phptrait ezcreflectionreturninfo { function getreturntype() { /*1*/ } function getreturndescription() { /*2*/ }}class ezcreflectionmethod extends reflectionmethod { use ezcreflectionreturninfo; /* ... */}class ezcreflectionfunction extends reflectionfunction { use ezcreflectionreturninfo; /* ... */}?>
1、先声明一个trait;
2、在类中使用use将该trait引入。
是不是非常简单(手动逃)?需要注意的是trait的优先级。
(免费学习视频分享:php视频教程)
5、trait的优先级
(敲黑板)从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。
优先级:自身方法>trait的方法>继承的方法(就是这样子的。)
看例子
<?phptrait helloworld { public function sayhello() { echo 'hello world!'; }}class theworldisnotenough { use helloworld; public function sayhello() { echo 'hello universe!'; }}$o = new theworldisnotenough();$o->sayhello();//输出是 hello universe!?>
还有一点需要注意的是:多个trait的使用。
<?phptrait hello { public function sayhello() { echo 'hello '; }}trait world { public function sayworld() { echo 'world'; }}class myhelloworld { use hello, world; public function sayexclamationmark() { echo '!'; }}$o = new myhelloworld();$o->sayhello();$o->sayworld();$o->sayexclamationmark();?>
总结:trait是一种代码复用技术,为php的单继承限制提供了一套灵活的代码复用机制。
相关推荐:php教程
以上就是php中trait如何使用的详细内容。
