The usual traditional mode of inheritance implies a simple hierarchy, for example:

class A { public function func_a() { echo 'work!'; } } class B extends A { public function func_b () { echo 'work B!'; } } class C extends A { public function func_c () { echo 'work C!'; } } $C = new C(); $C->func(); $C->func_c(); 

This is usually done, but I need to do so that it would be possible to call many others from one class. For example :

 $A = new A(); $A->func_c(); $A->func_b(); $A->func_a(); 

Here's how I implement this approach, while I need to extend the functionality of class A from other classes.

    1 answer 1

    An alternative can be treit or something samopisny based on magical methods.

    Starting with version 5.4.0, PHP introduces a toolkit for code reuse, called trait.

    Traits are 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 is 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 so-called c. 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.

    Multiple traits can be inserted into a class by listing them in a use directive, separated by commas.

    An example of using several traits

     <?php trait Hello { public function sayHello() { echo 'Hello '; } } trait World { public function sayWorld() { echo 'World'; } } class MyHelloWorld { use Hello, World; public function sayExclamationMark() { echo '!'; } } $o = new MyHelloWorld(); $o->sayHello(); $o->sayWorld(); $o->sayExclamationMark(); ?> 

    The result of this example:

     Hello World! 

    http://php.net/manual/ru/language.oop5.traits.php