The use of traits

Source: Internet
Author: User
Tags access properties traits
Original source: http://blog.csdn.net/longlongmylove/article/details/7521379

php5.4 New features traits introduction

1. Traits
Traits is a new method for implementing code reuse in 5.4.

PHP is a single-inheritance language, and we can't extends multiple base classes in a class like Java to implement code reuse, and now traits can solve the problem of code reuse, which allows developers to implement code reuse in a variety of classes.
Traits and class are defined in semantics to reduce the complexity of the code and avoid multiple inheritance problems.

Traits is similar to class, but it is used only to provide a set of functionality in a uniform and finer-grained manner, which cannot be instantiated within Traits, i.e. there is no class-like constructor __construct (). Traits is an extension of traditional PHP inheritance and enables horizontal integration, so you can no longer need inheritance in your application's class.

1) How to use
Use the keyword ' use ' In the class to refer to Traits. Multiple traits are separated by ', '.

The instance code is as follows:

[PHP] View plaincopy

    1. Trait Ezcreflectionreturninfo {
    2. function Getreturntype () {
    3. }
    4. function getreturndescription () {
    5. }
    6. }class ezcreflectionmethod extends reflectionmethod {
    7. Use Ezcreflectionreturninfo;
    8. /* ... */
    9. }
    10. class ezcreflectionfunction extends reflectionfunction {
    11. Use Ezcreflectionreturninfo;
    12. /* ... */
    13. }
    14. ?>

2) Priority level
The member functions in the base class will be overwritten by the functions in the traits, and the member functions in the current class will overwrite the functions in traits.

[PHP] View plaincopy

  1. class Base {
  2. Public function SayHello () {
  3. Echo ' Hello ';
  4. }
  5. }
  6. Trait Sayworld {
  7. Public function SayHello () {
  8. Parent::sayhello ();
  9. Echo "world!\n";
  10. }
  11. }
  12. class Myhelloworld extends Base {
  13. Use Sayworld;
  14. }
  15. class Myhelloworldext extends Base {
  16. Use Sayworld;
  17. Public function SayHello () {
  18. /**
  19. * Here is a new change in 5.4, the previous version of 5.4 will prompt:
  20. * PHP Fatal error:cannot Use string offset as an array
  21. * 5.4 is improved to return the character of the index number in the string
  22. */
  23. $str = "Arvin" ;
  24. Echo $str[0][0]; //Echo ' A ';
  25. }
  26. Public function shortarray () {
  27. $array = [' first ', 2, 3, 4]; simple syntax for arrays in//5.4
  28. Echo $array[0]; array element method in//5.4
  29. }
  30. }
  31. $o = New Myhelloworld ();
  32. $o ->sayhello ();
  33. $oe = New Myhelloworldext ();
  34. $oe ->sayhello ();
  35. Echo "\ n";
  36. $oe ->shortarray ();

[PHP] View plaincopy

    1. Output:
    2. Hello world!
    3. A
    4. First

3) Multi-traits

Multiple traits can be added to a class declaration, separated by "," between multiple traits.

[PHP] View plaincopy

  1. Trait Hello {
  2. Public function SayHello () {
  3. Echo ' Hello ';
  4. }
  5. }
  6. Trait World {
  7. Public function sayworld () {
  8. Echo ' world ';
  9. }
  10. }
  11. class Myhelloworld {
  12. Use Hello, world;
  13. }
  14. $o = New Myhelloworld ();
  15. $o ->sayhello ();
  16. $o ->sayworld ();
  17. ?>

Output Result:

Hello World 4) Multiple traits conflicts
If you add the same function name to the two traits in the same class and do not explicitly process it, an error will occur.
In order to resolve a function conflict of the same name in two tratis in the same class, you need to select the correct function with the insteadof operator.
Because of the uniqueness and exclusivity of the method, the ' as ' operator allows the use of the conflict function to resolve internal conflict issues.

[PHP] View plaincopy

  1. Trait A {
  2. Public function smallTalk () {
  3. Echo ' a ';
  4. }
  5. Public function bigtalk () {
  6. Echo ' A ';
  7. }
  8. }
  9. Trait B {
  10. Public function smallTalk () {
  11. Echo ' B ';
  12. }
  13. Public function bigtalk () {
  14. Echo ' B ';
  15. }
  16. }
  17. class Talker {
  18. Use A, B {
  19. B::smalltalk insteadof A;
  20. A::bigtalk insteadof B;
  21. }
  22. }
  23. class Aliased_talker {
  24. Use A, B {
  25. B::smalltalk insteadof A;
  26. A::bigtalk insteadof B;
  27. B::bigtalk as talk ;
  28. }
  29. }
  30. ?>

In the above example, talker uses traits A and B, so there is a conflict between the same function names in both.
Alker defines smalltalk taken from traits B,bigtalk taken from traits A.
Using the AS operator in Aliased_talker ensures that bigtalk in traits B is implemented by Alias talk.
5) Changing function access rights
We can use the AS syntax to change the access properties of functions in traits.

[PHP] View plaincopy

  1. Trait HelloWorld {
  2. Public function SayHello () {
  3. Echo ' Hello world! ' ;
  4. }
  5. }
  6. //change visibility of SayHello, changing the access rights of SayHello.
  7. class MyClass1 {
  8. Use HelloWorld {sayHello as protected;}
  9. }
  10. //Alias method with changed visibility
  11. //SayHello visibility not changed, set alias Myprivatehello.
  12. class MyClass2 {
  13. Use HelloWorld {sayHello as private Myprivatehello;}
  14. }
  15. ?>

6) Traits composition of the new traits
As with many classes, you can use traits in the same class as in Traits,traits. One or more traits can be defined in one traits, and these traits can be defined in other traits as part or all of the members.

[PHP] View plaincopy

  1. Trait Hello {
  2. Public function SayHello () {
  3. Echo ' Hello ';
  4. }
  5. }
  6. Trait World {
  7. Public function sayworld () {
  8. Echo ' world! ' ;
  9. }
  10. }
  11. Trait HelloWorld {
  12. Use Hello, world;
  13. }
  14. class Myhelloworld {
  15. Use HelloWorld;
  16. }
  17. $o = New Myhelloworld ();
  18. $o ->sayhello ();
  19. $o ->sayworld ();
  20. ?>

The above routines will output:

[PHP] View plaincopy

    1. Hello world!

7) Abstract Trait members
In order to enforce some methods in a class, you can use an abstract method in traits.
For example:

[PHP] View plaincopy

  1. Trait Hello {
  2. Public function sayhelloworld () {
  3. Echo ' Hello '. $this ->getworld ();
  4. }
  5. Abstract public Function Getworld ();
  6. }
  7. class Myhelloworld {
  8. Private $world;
  9. Use Hello;
  10. Public function __construct ($world) {
  11. $this ->world = $world ;
  12. }
  13. Public function getworld () {
  14. return $this->world;
  15. }
  16. }
  17. /**
  18. * Here are 5.4 new feature class instances to dissolve the reference operation
  19. * (new Class ())->method ();
  20. */
  21. (new myhelloworld (' Arvin '))->sayhelloworld ();
  22. ?>
  23. The instance output:
  24. Hello Arvin

8) Static Trait members

Static variables cannot be defined in traits, but can be defined in Tratis functions. Static functions can also be defined in Tratis.

[PHP] View plaincopy

  1. Trait Counter {
  2. Public function Inc () {
  3. Static $c = 0; //static variable
  4. $c + = 1;
  5. Echo "$c \ n";
  6. }
  7. /**
  8. * static Method
  9. */
  10. Public static function dosomething () {
  11. Echo ' Doing something ';
  12. }
  13. }
  14. class C1 {
  15. Use Counter;
  16. }
  17. (new C1 ())->inc (); //Echo 1
  18. C1::d osomething ();
  19. ?>
  20. The output is:
  21. 1
  22. Doing something

9) Traits defining attributes

If a property is defined in a trait, a property with the same name cannot be defined in the class that references the trait, if the defined attribute in the class has the same name and access visibility as the defined property in trait, it is a e_strict Prompt, otherwise throws a syntax error.

 
                             x, $example->y;? > Output: 12

At the end of the post php5.4.0 part of the new feature Changelog:

Added Short array syntax support ([All-in-A-z]), see Upgrading Guide for full details. Added binary numbers Format (0b001010). Added Support for CLASS::{EXPR} () syntax. Added support for traits.//The main content of this article Added closure $this support back. Added array dereferencing support.//arrays are supported, with an instance Added callable Typehint above. Added indirect method call through array. #47160. Added DTrace support.//legend DTrace is a profiling tool that can track data such as function call points, return points, Added class member access on instantiation (e.g. new Foo)->bar ()) support.//class new instance dereference operation, with instance
The purpose of this paper is to explore the new features of php5.4 together. ^_^

The above describes the use of traits, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.