Search code examples
phpmixins

Is it possible to use mixins in php


I came to know about mixins.So my doubt is, is it possible to use mixins in php?If yes then how?


Solution

  • Use Trait introduced in PHP 5.4

    <?php
    class Base {
        public function sayHello() {
            echo 'Hello ';
        }
    }
    
    trait SayWorld {
        public function sayHello() {
            parent::sayHello();
            echo 'World!';
        }
    }
    
    class MyHelloWorld extends Base {
        use SayWorld;
    }
    
    $o = new MyHelloWorld();
    $o->sayHello();
    ?>
    

    which prints Hello World!

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