PHP的Trait 特性

Trait是在PHP5.4中加入的,它既不是接口也不是类。主要是为了解决单继承语言的限制。是PHP多重继承的一种解决方案。例如,需要同时继承两个 Abstract Class, 这将会是件很麻烦的事情,Trait 就是为了解决这个问题。它能被加入到一个或多个已经存在的类中。它声明了类能做什么(表明了其接口特性),同时也包含了具体实现(表明了其类特性)。

简单使用

首先,当然是声明个 Trait,PHP5.4 增加了 trait 关键字

Trait是在PHP5.4中加入的,它既不是接口也不是类。主要是为了解决单继承语言的限制。是PHP多重继承的一种解决方案。例如,需要同时继承两个 Abstract Class, 这将会是件很麻烦的事情,Trait 就是为了解决这个问题。它能被加入到一个或多个已经存在的类中。它声明了类能做什么(表明了其接口特性),同时也包含了具体实现(表明了其类特性)。

简单使用
  首先,当然是声明个 Trait,PHP5.4 增加了 trait 关键字

同时,如果要在 Class 中使用该 Trait,那么使用 use 关键字

class first_class {
   // 注意这行,声明使用 first_trait
   use first_trait;
}
$obj = new first_class();
// Executing the method from trait
$obj->first_method(); // valid
$obj->second_method(); // valid

使用多个 Trait

在同个 Class 中可以使用多个 Trait

trait first_trait
{
    function first_method() { echo "method1"; }
}
trait second_trait {
    function second_method() { echo "method2"; }
}
class first_class {
    // now using more than one trait
    use first_trait, second_trait;
}
$obj= new first_class();
// Valid
$obj->first_method(); // Print : method1
// Valid
$obj->second_method(); // Print : method2

Trait 之间的嵌套

同时,Trait 之间也可以相互的嵌套,例如

    function first_method() { echo "method1"; }
}
trait second_trait {
    use first_trait;
    function second_method() { echo "method2"; }
}
class first_class {
    // now using 
    use second_trait;
}
$obj= new first_class();
// Valid
$obj->first_method(); // Print : method1
// Valid
$obj->second_method(); // Print : method2```

### Trait 的抽象方法(Abstract Method)
我们可以在 Trait 中声明需要实现的抽象方法,这样能使使用它的 Class 必须实现它
~~`
trait first_trait {
    function first_method() { echo "method1"; }
    // 这里可以加入修饰符,说明调用类必须实现它
    abstract public function second_method();
}
class first_method {
    use first_trait;
    function second_method() {
        /* Code Here */
    }
}

Trait 冲突

```trait first_trait {
    function first_function() {
        echo "From First Trait";
    }
}
trait second_trait {
    // 这里的名称和 first_trait 一样,会有冲突
    function first_function() {
        echo "From Second Trait";
    }
}
class first_class {
    use first_trait, second_trait {
        // 在这里声明使用 first_trait 的 first_function 替换
        // second_trait 中声明的
        first_trait::first_function insteadof second_trait;
    }
}
$obj = new first_class();
// Output: From First Trait
$obj->first_function();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值