views:

356

answers:

3

I have a class which I need to use to extend different classes (up to hundreds) depending on criteria. Is there a way in PHP to extend a class by a dynamic class name?

I assume it would require a method to specify extension with instantiation.

Ideas?

+1  A: 

Take a look at this, where someone else wondered the same thing and came up with a partial solution.

luvieere
That is quite interesting, however what I need is the reverse. I need to dynamically specify the parent.
Spot
+3  A: 

I don't think it's possible to dynamically extend a class (however if I'm wrong I'd love to see how it's done). Have you thought about using the Composite pattern (http://en.wikipedia.org/wiki/Composite%5Fpattern, http://devzone.zend.com/article/7)? You could dynamically composite another class (even multiple classes - this is often used as a work around to multiple inheritance) to 'inject' the methods/properties of your parent class into the child class.

Arms
Thank you very much.
Spot
A: 

Couldn't you just use an eval?

<?php
function dynamic_class_name() {
    if(time() % 60)
        return "Class_A";
    if(time() % 60 == 0)
        return "Class_B";
}
eval(
    "class MyRealClass extends " . dynamic_class_name() . " {" . 
    # some code string here, possibly read from a file
    . "}"
);
?>
Leafy
I am usually very hesitant to use eval() in any kind of a production environment.
Spot