【PHP】面向对象 - trait关键字

小破孩
2022-06-19 / 0 评论 / 174 阅读 / 正在检测是否收录...

PHP是单继承语言,因此一个类不能同时继承多个类。

Trait的出现主要是为了解决单继承语言的局限性问题,是PHP多重继承的一种解决方法。
trait不是类,所以不能有静态成员、类常量,当然也不可能被实例化。
创建新文件来声明Trait:

    trait first_trait
     {
        function first_method() { /* Code Here */ }
    
    }

在类中使用 use + trait名进行引用即可,引用之后就可以使用trait中声明的方法。

    class test
    {
        use first_trait;
        private $method;
        public function __construct()
        {
            $this->method = $this->first_method();    
        }
    }
0

评论 (0)

取消