Introduction to new features of php5.4 Traits
1. traits
Traits is a newly added method in 5.4 for code reuse.
Php is a single inherited language. We cannot use multiple base classes in a class like java to reuse code. Now Traits can solve this problem of code reuse, it allows developers to reuse code in multiple different classes.
Both Traits and class are defined in semantics to reduce Code complexity and avoid multiple inheritance issues.
Traits is similar to class, but it is only used to provide a set of functions in a unified and fine-grained manner. It cannot be instantiated within Traits, that is, the constructor _ construct () similar to the class does not exist (). Traits is a traditional extension of php and implements horizontal integration. Therefore, you do not need to inherit from the class of the application.
1) How to Use
Use the keyword 'use' in the class to reference Traits. Multiple Traits are separated by commas.
The instance code is as follows:
<?phptrait ezcReflectionReturnInfo {function getReturnType() {}function getReturnDescription() {}}class ezcReflectionMethod extends ReflectionMethod {use ezcReflectionReturnInfo;/* ... */}class ezcReflectionFunction extends ReflectionFunction {use ezcReflectionReturnInfo;/* ... */}?>
2) Priority
The member functions in the base class will be overwritten by the functions in Traits. The member functions in the current class will overwrite the functions in Traits.
<? Phpclass Base {public function sayHello () {echo 'hello' ;}} trait SayWorld {public function sayHello () {parent: sayHello (); echo "World! \ N ";}} class MyHelloWorld extends Base {use SayWorld;} class MyHelloWorldExt extends Base {use SayWorld; public function sayHello () {/*** here is a new change in 5.4. In versions earlier than 5.4, the following error occurs: * PHP Fatal error: cannot use string offset as an array * 5.4 is improved to the character */$ str = "Arvin"; echo $ str [0] [0] in the returned string. // echo 'a';} public function shortArray () {$ array = ['first', 2, 3, 4]; // simple array syntax echo $ array [0] in 5.4; // Method for retrieving array elements from arrays in 5.4} $ o = new MyHelloWorld (); $ o-> sayHello (); $ oe = new MyHelloWorldExt (); $ oe-> sayHello (); echo "\ n"; $ oe-> shortArray ();
Output: Hello World! Afirst
3) Multi-Traits
Multiple Traits can be added to the declaration of a class. Multiple Traits are separated by commas.
<?phptrait Hello { public function sayHello() { echo 'Hello '; }}trait World { public function sayWorld() { echo 'World'; }}class MyHelloWorld { use Hello, World;}$o = new MyHelloWorld();$o->sayHello();$o->sayWorld();?>
Output result:
Hello World
4) Multi-Traits conflict
If the two Traits added to the same class have the same function name and are not explicitly processed, an error is generated.
To resolve the conflict between functions with the same name in two Tratis in the same class, you need to use the insteadof operator to select the correct function.
Because the method is unique and exclusive, the 'as' operator can be used after conflicting functions to solve internal conflicts.
<?phptrait A {public function smallTalk() {echo 'a';}public function bigTalk() {echo 'A';}}trait B {public function smallTalk() {echo 'b';}public function bigTalk() {echo 'B';}}class Talker {use A, B {B::smallTalk insteadof A;A::bigTalk insteadof B;}}class Aliased_Talker {use A, B {B::smallTalk insteadof A;A::bigTalk insteadof B;B::bigTalk as talk;}}?>
In the preceding example, Talker uses Traits A and B, so the same function names in the two are in conflict.
Alker defines that smallTalk is taken from Traits B and bigTalk is taken from Traits.
In Aliased_Talker, The as operator is used to ensure that bigTalk in Traits B is implemented through the alias talk.
5) change function Access Permissions
We can use the as syntax to change the access permission attribute of functions in Traits.
<? Phptrait HelloWorld {public function sayHello () {echo 'Hello World! ';}} // Change visibility of sayHello to Change the access permission of sayHello. Class MyClass1 {use HelloWorld {sayHello as protected; }}// Alias method with changed visibility // sayHello visibility not changed, set the Alias myPrivateHello. Class MyClass2 {use HelloWorld {sayHello as private myPrivateHello ;}}?>
6) Traits to form a new Traits
Like many classes, you can use Traits in the class, and you can use Traits in the Traits. One or more Traits can be defined in a Traits, which can be defined in other Traits as part or all members.
<?phptrait Hello {public function sayHello() {echo 'Hello ';}}trait World {public function sayWorld() {echo 'World!';}}trait HelloWorld {use Hello, World;}class MyHelloWorld {use HelloWorld;}$o = new MyHelloWorld();$o->sayHello();$o->sayWorld();?>
The above routine will output:
Hello World!
7) Abstract Trait Member
To enforce certain methods in a class, you can use abstract methods in traits.
For example:
<? Phptrait Hello {public function sayhelloworld () {echo 'Hello '. $ this-> getworld ();} Abstract Public Function getworld ();} class myhelloworld {private $ world; Use hello; public function _ construct ($ World) {$ this-> world = $ world;} public function getworld () {return $ this-> world ;}} /*** here the new function 5.4 class instance resolution reference operation is used * (New Class ()-> method (); */(New myhelloworld ('arvin ')) -> sayhelloworld ();?> Output of this instance: Hello Arvin
8) Static trait members
Static static variables cannot be defined in traits, but can be defined in the tratis function. You can also define static functions in tratis.
<? Phptrait counter {public function Inc () {static $ C = 0; // static variable $ C + = 1; echo "$ C \ n ";} /*** Static Method */public static function dosomething () {echo 'Doing something ';} Class C1 {use counter;} (New C1 ()) -> Inc (); // echo 1C1: dosomething ();?> Output: 1 doing something
9) Traits defined attributes
If an attribute is defined in a trait, the attributes with the same name cannot be defined in the class that references the trait, if the attributes defined in this class have the same name and access visibility as those defined in traitE_STRICT
Prompt. Otherwise, a syntax error is thrown.
<? Phptrait PropertiesTrait {public $ x = 1; public $ y = 2;} class PropertiesExample {use PropertiesTrait; public $ x = 1; // public $ y = 3 ;} $ example = new PropertiesExample; echo $ example-> x, $ example-> y;?> Output: 12
At the end, paste the new function changelog in php5.4.0:
Added short array syntax support ([1, 2, 3]), see UPGRADING guide for full details. added binary numbers format (0b001010 ). added support for Class ::{ expr} () syntax. added support for Traits. // Added closure $ this support back. added array dereferencing support. // supports Array Decoding. The preceding example shows the instance Added callable typehint. added indirect method call through array. #47160. added DTrace support. // It is said that DTrace is a performance analysis tool that can track function call points, return points, and other data. Added class member access on instantiation (e.g. (new foo)-> bar () support. // a new instance of the class is used to unreference the instance.
This article aims to encourage you to continue exploring new features of php5.4. Pai_^