PHP之Trait详解
<?php trait Dog{ public $name="dog"; public function bark(){ echo "This is dog"; } } class Animal{ public function eat(){ echo "This is animal eat"; } } class Cat extends Animal{ use Dog; public function drive(){ echo "This is cat drive"; } } $cat = new Cat(); $cat->drive(); echo "<br/>"; $cat->eat(); echo "<br/>"; $cat->bark(); ?>
This is cat drive This is animal eat This is dog
<?php trait Dog{ public $name="dog"; public function drive(){ echo "This is dog drive"; } public function eat(){ echo "This is dog eat"; } } class Animal{ public function drive(){ echo "This is animal drive"; } public function eat(){ echo "This is animal eat"; } } class Cat extends Animal{ use Dog; public function drive(){ echo "This is cat drive"; } } $cat = new Cat(); $cat->drive(); echo "<br/>"; $cat->eat();
This is cat drive This is dog eat
use trait1,trait2
<?php trait trait1{ public function eat(){ echo "This is trait1 eat"; } public function drive(){ echo "This is trait1 drive"; } } trait trait2{ public function eat(){ echo "This is trait2 eat"; } public function drive(){ echo "This is trait2 drive"; } } class cat{ use trait1,trait2{ trait1::eat insteadof trait2; trait1::drive insteadof trait2; } } class dog{ use trait1,trait2{ trait1::eat insteadof trait2; trait1::drive insteadof trait2; trait2::eat as eaten; trait2::drive as driven; } } $cat = new cat(); $cat->eat(); echo "<br/>"; $cat->drive(); echo "<br/>"; echo "<br/>"; echo "<br/>"; $dog = new dog(); $dog->eat(); echo "<br/>"; $dog->drive(); echo "<br/>"; $dog->eaten(); echo "<br/>"; $dog->driven(); ?>
This is trait1 eat This is trait1 drive This is trait1 eat This is trait1 drive This is trait2 eat This is trait2 driv
<?php trait Animal{ public function eat(){ echo "This is Animal eat"; } } class Dog{ use Animal{ eat as protected; } } class Cat{ use Animal{ Animal::eat as private eaten; } } $dog = new Dog(); $dog->eat();//报错,因为已经把eat改成了保护 $cat = new Cat(); $cat->eat();//正常运行,不会修改原先的访问控制 $cat->eaten();//报错,已经改成了私有的访问控制 ?
<?php trait Cat{ public function eat(){ echo "This is Cat eat"; } } trait Dog{ use Cat; public function drive(){ echo "This is Dog drive"; } abstract public function getName(); public function test(){ static $num=0; $num++; echo $num; } public static function say(){ echo "This is Dog say"; } } class animal{ use Dog; public function getName(){ echo "This is animal name"; } } $animal = new animal(); $animal->getName(); echo "<br/>"; $animal->eat(); echo "<br/>"; $animal->drive(); echo "<br/>"; $animal::say(); echo "<br/>"; $animal->test(); echo "<br/>"; $animal->test(); ?
This is animal name This is Cat eat This is Dog drive This is Dog say 1 2