Wednesday, June 9, 2010

Multiple Inheritance with PHP

Right now at work, I'm implementing classes in PHP for an Interactive Design Tool which will allow us to select fields from multiple tables and multiple sources, and then automatically generate the CloverETL XML graphs used to execute the data tranformations to create a new Datamart. I came across a case where I wanted one class to inherit methods and members from more than one other class. This type of behaviour is not supported by PHP, but I came across some hack-ish ways to facilitate it.


class b {
public function thisisB($e) {
print "This is B $e\n";
}
}

class c {
public function thisisC($e) {
print "This is C $e";
}
}

class a extends b {
function __construct() {
$this->c = new c();
}

public function __call($method,$args) {
$this->c->$method($args[0]);
}
}

$a = new a();
$a->thisisB("from A");
$a->thisisC("from A");

The output will be:


This is B from A
This is C from A

The __call method will capture any function call that doesn't already have a function definition in the class (or it's inherited classes) and the arguments. From here, we've made a member object of class c inside class a, so we can pass any unregocnized calls onto $this->c, and we'll have access to the methods of class c. It's not perfect, and it's a little ugly, but it works and does what you would expect.

No comments:

Post a Comment