PHP5.4 after the new traits implementation of code reuse mechanism, trait and class similar, but can not be instantiated, do not need to inherit, only in the class using the keyword use to introduce can be introduced into a number of traits, with ', ' separated.
(1) Trait simple use
<?php
trait A {public
$var 1 = ' test1 ';
Public Function test1 () {
echo ' trait a::test1 () ';
}
}
Trait B {public
$var 2 = ' 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 issues
Trait overrides the inherited method, and the current class overrides the trait method.
Trait A {public
$var 1 = ' 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 conflict issues
If the conflict is not resolved, a fatal error is generated;
Insteadof can be used to identify which approach to use in a conflict;
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 as another
(4) As can be used to modify the method access control
Trait HelloWorld {public
function SayHello () {
echo ' Hello world! ';
}
}
Modify SayHello access Control
class A {use
HelloWorld {SayHello as protected;}
}
Give the method a change of access control alias
//original SayHello access control is not changed
class B {use
HelloWorld {SayHello as Private Myprivatehell o; }
}
$b = new A ();
$b->sayhello (); Fatal Error:call to protected Method A::sayhello () from the context '
(5) Use of 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, supports static methods, and can not directly define static variables, but static variables can be referenced by trait methods.
Trait A {public
function test1 () {
static $a = 0;
$a + +;
echo $a;
}
Abstract public Function test2 (); Can define abstract method
}
class B {use
A;
Public Function Test2 () {
}
}
$b = new B ();
$b->test1 (); 1
$b->test1 ();//2
(7) Trait can be defined, but the same name property cannot be defined in a class
Trait A {public
$test 1;
}
Class B {use
A;
Public $test 2;
}