版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34804120/article/details/86429750
什么是trait?
自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。
class Article
{
public function owner()
{
var_dump('this thing has owner');
}
}
class Comment
{
public function owner()
{
var_dump('this thing has owner');
}
}
Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。从而引入了trait。
trait OwnerTrait
{
public function owner()
{
var_dump('this thing has owner');
}
}
class Article
{
use OwnerTrait;
}
class Comment
{
use OwnerTrait;
}
(new Article())->owner();
trait为我们带来了什么?
- 代码复用
- 在别人的代码(旧代码)中插入自己的代码