Trait trong PHP

 Trong PHP KHÔNG hỗ trợ multiple inheritance, vì vậy việc viết như sau là không khả thi


class A extends class B, extends class C --> không được

Tuy nhiên sẽ có nhiều trường hợp, từ class A, bạn muốn dùng các method của class B và class C. Vậy phải làm thế nào?

Đó là lý do Trait ra đời.


https://stackoverflow.com/questions/356128/can-i-extend-a-class-using-more-than-1-class-in-php 

Có đề cập đến định nghĩa khá ngắn gọn và dễ hiểu về trait


You could use traits, which, hopefully, will be available from PHP 5.4.

Traits is 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.

They are recognized for their potential in supporting better composition and reuse, hence their integration in newer versions of languages such as Perl 6, Squeak, Scala, Slate and Fortress. Traits have also been ported to Java and C#.

Comments

Popular posts from this blog

Các câu hỏi liên quan đến restful API

Active record (Eloquent) trong Laravel và Data Mapper (Doctrine) trong Symfony

CI/CD diagram, infra