<?php
/*
* PHP trait类代码复用
* trait实现了代码的复用
* 并且突破了单继承的限制
* trait 是类又不是类,不能实例化
* trait 相当于代码复制,即通过use 把Demo1类和Demo2类中的方法复制到Demo类中,实现了Demo类继承了Demo1类和Demo2类中的方法
*/
trait Demo1{
public function hello1(){
return __METHOD__;
}
}
trait Demo2{
public function hello2(){
return __METHOD__;
}
}
class Demo{
// 在Demo类中继承Demo1、demo2类,使用use
use Demo1,Demo2;
public function hello(){
return __METHOD__;
}
public function test1(){
// 在test1方法中访问Demo1中的hello1方法
return $this->hello1();
}
public function test2(){
// 在test2方法中访问Demo2中的hello2方法
return $this->hello2();
}
}
$obj = new Demo;
echo $obj->hello(); // 输出Demo中的hello();
echo '<hr>';
echo $obj->test1() // 通过trait实现在Demo类中输出Demo1中的hello1()方法
echo '<hr>';
echo $obj->test2() // 通过trait实现在Demo类中输出Demo2中的hello2()方法
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号