PHP's traits implements code reuse using instances, phptraits
After PHP5.4, a new traits implementation code reuse mechanism is added. Trait is similar to a class, but it cannot be instantiated. Without inheritance, you only need to use the keyword use in the class to introduce multiple Traits, separated by commas.
(1) simple use of Trait
<?php trait A { public $var1 = 'test1'; public function test1() { echo 'trait A::test1()'; }} trait B { public $var2 = 'test2'; public function test2() { echo 'trait B::test2()'; }} class C { use A,B;} $c = new C();echo $c->var1; //test1$c->test2(); //trait B::test2()
(2) Priority
Trait will overwrite the inherited method, and the current class will overwrite the Trait method.
trait A { public $var1 = 'test'; public function test() { echo 'A::test()'; } public function test1() { echo 'A::test1()'; }} class B { public function test() { echo 'B::test()'; } public function test1() { echo 'B::test1()'; }}class C extends B{ use A; public function test() { echo 'c::test()'; }} $c = new C();$c->test(); //c::test()$c->test1(); //A::test1()
(3) Multiple Trait conflicts
If the conflict is not resolved, a fatal error occurs;
Insteadof can be used to determine which method of conflict is used;
Use the as operator to name one of the conflicting methods;
Trait A {public function test () {echo 'a: test () ';}} trait B {public function test () {echo' B: test () ';}} class C {use A, B {B: test insteadof A; B: test as t ;}}$ c = new C (); $ c-> test (); // B: test () $ c-> t (); // B: test () can be named by another name.
(4) as can be used to modify method Access Control
Trait HelloWorld {public function sayHello () {echo 'Hello World! ';}} // Modify the access control class A {use HelloWorld {sayHello as protected;} of sayHello ;}} // give the method an access control alias that has changed the access control // The access control of the original sayHello does not change class B {use HelloWorld {sayHello as private myPrivateHello ;}} $ B = new A (); $ B-> sayHello (); // Fatal error: Call to protected method A: sayHello () from context''
(5) Use Trait in Trait
trait A { public function test1() { echo 'test1'; }} trait B { public function test2() { echo 'test2'; }} trait C { use A,B;} class D { use C;} $d = new D();$d->test2(); //test2
(6) Trait supports abstract methods, static methods, and cannot directly define static variables. However, static variables can be referenced by the trait method.
Trait A {public function test1 () {static $ a = 0; $ a ++; echo $ a;} abstract public function test2 (); // definable abstract method} class B {use A; public function test2 () {}}$ B = new B (); $ B-> test1 (); // 1 $ B-> test1 (); // 2
(7) Trait can define attributes, but the same name attribute cannot be defined in the class.
trait A { public $test1;} class B { use A; public $test2;}