I came to know about mixins.So my doubt is, is it possible to use mixins in php?If yes then how?
Request for Comments: mixin This is first draft of adding the 'mixin' keyword into the PHP language. It based around the 'trait' proposal where the primary advantage is to avoid code duplication and re-factoring of code.
PHP's implementation of traits does allow states to be used, and therefore traits in PHP are actually mixins.
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.
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
This answer is obsolete as of PHP 5.4. See Jeanno's answer for how to use traits.
It really depends on what level of mixins
you want from PHP. PHP handles single-inheritance, and abstract classes, which can get you most of the way.
Of course the best part of mixins is that they're interchangeable snippets added to whatever class needs them.
To get around the multiple inheritance issue, you could use include
to pull in snippets of code. You'll likely have to dump in some boilerplate code to get it to work properly in some cases, but it would certainly help towards keeping your programs DRY.
Example:
class Foo { public function bar( $baz ) { include('mixins/bar'); return $result; } } class Fizz { public function bar( $baz ) { include('mixins/bar'); return $result; } }
It's not as direct as being able to define a class as class Foo mixin Bar
, but it should get you most of the way there. There are some drawbacks: you need to keep the same parameter names and return variable names, you'll need to pass other data that relies on context such as func_get_args_array
or __FILE__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With