Is it possible to inherit properties and methods from several classes in php? if yes, please take an example

    2 answers 2

    Is it possible to inherit properties and methods from several classes in php?

    Pure - not, but since version 5.4.0, PHP has been implementing a method for reusing code called trait.

    Quote:


    Trait is a mechanism for ensuring code reuse in languages ​​with support for only single inheritance, such as PHP. The trait is designed to reduce some of the limitations of single inheritance, allowing the developer to reuse sets of methods freely, in several independent classes and implemented using different class building architectures. The semantics of the combination of traits and classes are defined in such a way as to reduce the level of complexity, as well as to avoid the typical problems associated with multiple inheritance and mixing (mixins).

    A trait is very similar to a class, but it is intended to group functionalities in a well-structured and consistent manner. Cannot create a standalone copy of the trait. This addition to the usual inheritance and allows you to make a horizontal composition of behavior, that is, the use of class members without the need for inheritance.

    Example:

    <?php trait ezcReflectionReturnInfo { function getReturnType() { /*1*/ } function getReturnDescription() { /*2*/ } } class ezcReflectionMethod extends ReflectionMethod { use ezcReflectionReturnInfo; /* ... */ } class ezcReflectionFunction extends ReflectionFunction { use ezcReflectionReturnInfo; /* ... */ } 

    * You can read more in the official documentation at the link above.

      If you need it in PHP, then it's time to implement interfaces . Properties you do not inherit, but again if you need it, it's time to get rid of them in favor of the methods.