How to use traits in Laravel 5.4.18?

前端 未结 3 1618
清酒与你
清酒与你 2021-01-12 09:06

I need an example of where to exactly create the file, to write to it, and how to use the functions declared in the trait. I use Laravel Framework 5.4.18

3条回答
  •  萌比男神i
    2021-01-12 09:31

    Trait description:

    Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.

    The solution

    Make a directory in your App, named Traits

    Create your own trait in Traits directory ( file: Sample.php ):

    Then use it in your own controller:

    Now the MyController class has the testMethod method inside.

    You can change the behavior of trait methods by overriding them it in MyController class:

提交回复
热议问题