<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/10/9 0009
* Time: 下午 9:44
*/
trait Drive {
public $carName = 'trait';
public function driving() {
echo "driving {$this->carName}<br>";
}
}
class Person {
public function eat() {
echo "eat<br>";
}
}
//Student 继承了 基类Person 拥有了基类中的eat方法, 通过use [trait Drive] 可以使用trait 中的 driving方法
// trait解决了单继承的局限性
class Student extends Person {
use Drive;
public function study() {
echo "study<br>";
}
}
$student = new Student();
$student->study();
$student->eat();
// Notice: Undefined variable: carName
//$student->$carName;
$student->driving();
trait Say1{
public function hi(){
echo 'say hi from say1<br>';
}
public function hello(){
echo 'say hello from say1<br>';
}
}
trait Say2{
public function hi(){
echo 'say hi from say2<br>';
}
public function hello(){
echo 'say hello from say2<br>';
}
}
class ClassSay{
use Say1,Say2{
//使用insteadof 来解决不同trait中的同名方法
Say1::hello insteadof Say2;// say1 中的hello方法 取代 say2的hello方法
Say2::hi insteadof Say1; // say2的hi方法 取代 say1的 hi方法
// trait方法取别名
Say2::hello as heihei; //哪怕上面使用insteadof 这里的heihei别名对应的是trait原有的方法
Say1::hi as hehe;
}
}
$csay = new ClassSay;
$csay->hello();
$csay->hi();
$csay->heihei();//say hello from say2
$csay->hehe();//say hi from say1
// trait中可以使用 trait , trait中可以有抽象方法, 静态方法 静态变量
trait T1{
public function hi(){
echo 't1 hi';
}
}
trait T2{
use T1;
public abstract function absMethod();
}
class Class3{
use T2;
public function absMethod(){
echo 'Class3 abs method impl'.'<br>';
}
public function staticMethod(){
static $i = 0;
$i++;
echo 'Class3 staticMethod:'.$i.'<br>';
}
}
$c3 = new Class3();
$c3->absMethod();
$c3->staticMethod();
$c3->staticMethod();
/*
* 输出结果:
study
eat
driving trait
say hello from say1
say hi from say2
say hello from say2
say hi from say1
Class3 abs method impl
Class3 staticMethod:1
Class3 staticMethod:2
*/
php中trait使用
最新推荐文章于 2023-10-30 17:09:17 发布