on Mar 22nd, 2008Ruby-style mixins in PHP

This is a rather hackish way to accomplish something resembling ruby’s mixins, I doubt it we will ever be able to do this as elegantly as in ruby. This is the closest I can come to true mixins, without using ext/runkit.

<?php
class TargetTest {
    var $prepend = "Printing: %s\n";
    static $__mixins__ = array();

    function __call($func, $args) {
        if ($function = @self::$__mixins__[$func]) {
            array_unshift($args, $this);
            return call_user_func_array($function, $args);
        }
    }

    function print_int($integer) {
        printf($this->prepend, $integer);
    }
}

abstract class MixinTest {
    static function print_string($self, $string) {
        printf($self->prepend, $string);
    }
}

function mixin($target, $mixin) {
    $methods = get_class_methods($mixin);
    foreach ($methods as $method) {
        eval("$target::\$__mixins__['$method'] = array('$mixin','$method');");
    }
}

mixin('TargetTest', 'MixinTest');
$target = new TargetTest;
$target->print_int(123);
$target->print_string('Heeey');

2 Responses to “Ruby-style mixins in PHP”

  1. Raphaëlon 26 Mar 2008 at 9:03 am

    You should take a look at PHP Traits : http://www.stefan-marr.de/rfc-traits-for-php.txt (expected to be included in PHP 5.4)

  2. Fredrik Holmströmon 26 Mar 2008 at 1:04 pm

    So they did accept this for PHP5.4? I’ve read Stefan’s proposal before - didn’t know they accepted it into the 5.4.X-branch.

Trackback URI | Comments RSS

Leave a Reply