Archiv

Archiv für die Kategorie ‘php’

Multiple Inheritance in PHP

20. Dezember 2009 Keine Kommentare

With the magic of __call() it is possible to do multiple inheritance in PHP. This example is more then a mixin pattern. It can call protected and private methods from inherited classes, too.

<?php

abstract class Inheritance {
    private $_inheritances = array();

    public function __call($method, array $arguments = array()) {
        // Here you can handle the calls. Maybe you don't want to call
        // every found method but only the first or the last ...
        foreach ($this->_inheritances as $inheritance) {
            $inheritance->invoke($method, $arguments);
        }
    }

    public function invoke($method, $arguments) {
        if (method_exists($this, $method) === true) {
            return call_user_func_array(array($this, $method), $arguments);
        }
    }

    protected function _addInheritance(Inheritance $inheritance) {
        $this->_inheritances[get_class($inheritance)] = $inheritance;
    }
}

That’s all! Now the usage:

We have two simple base classes, Bird and Horse, which have some methods.

/**
 * first base class
 */
class Bird extends Inheritance {
    public function chirp() {
        echo "<br/>chirp ..";
    }

    public function fly() {
        echo "<br/>fly ..";
    }

    protected function _eat() {
        echo "<br/>eat worms ..";
    }
}

/**
 * second base class
 */
class Horse extends Inheritance {
    public function whinny() {
        echo "<br/>whinny ..";
    }

    protected function _eat() {
        echo "<br/>eat hay ..";
    }
}

Now we want a new class named Pegasus that implements all methods from Bird and Horse. The only thing we have to do is to inherit from Inheritance and add the two base classes with _addInheritance().

class Pegasus extends Inheritance {
    public function __construct() {
        // bind extented classes
        $this->_addInheritance(new Bird);
        $this->_addInheritance(new Horse);
    }

    public function eat() {
        // works with protected methods, too
        $this->_eat();
    }
}

$pegasus = new Pegasus;
$pegasus->chirp();
$pegasus->fly();
$pegasus->whinny();
$pegasus->eat();

Output:

chirp ..
fly ..
whinny ..
eat worms ..
eat hay ..
Kategorienphp

Chaining Variables

21. Juni 2009 Keine Kommentare

Do you have always asked yourself how to chain variables to make a sentence?

In the magic __get()-method the variable names will be collected, and finally the echo “calls” the __toString()-method.

<?php

class Sentence {
    protected $_words = array();

    public static function create() {
        return new self;
    }

    public function __get($word) {
        $this->_words[] = $word;

        return $this;
    }

    public function __toString() {
        return implode(' ', $this->_words) . '.';
    }
}

Usage:

echo Sentence::create()->All->your->base->are->belong->to->us;

Output:

All your base are belong to us.
Kategorienphp