Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use mixins in php

Tags:

php

mixins

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

like image 592
NewUser Avatar asked Jul 29 '11 17:07

NewUser


People also ask

What is mixin in PHP?

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.

Are PHP traits mixins?

PHP's implementation of traits does allow states to be used, and therefore traits in PHP are actually mixins.

What is a trait PHP?

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.


2 Answers

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

like image 195
Jeanno Avatar answered Oct 05 '22 12:10

Jeanno


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__.

like image 41
zzzzBov Avatar answered Oct 05 '22 12:10

zzzzBov