Is it possible to extend a class dynamically?

Viewed 23406

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?

9 Answers

I have solved my same type of problem. The first parameter defines the original class name and the second parameter defines the new class name of class_alias function. Then we can use this function in if and else condition.

if(1==1){
  class_alias('A', 'C');
}
else{
  class_alias('B', 'C');
}

class Apple extends C{
      ...
}

Apple class extends to virtual class "C" which can be defined as class "A" Or "B" depend on if and else condition.

For More information you can check this link https://www.php.net/manual/en/function.class-alias.php

I had to do this with a processor class that extends one of two abstract classes.

The working solution looks like this:

if (class_exists('MODX\Revolution\Processors\Processor')) {
    abstract class DynamicProcessorParent extends 
        MODX\Revolution\Processors\Processor {}
} else {
    abstract class DynamicProcessorParent extends modProcessor {}
}

class NfSendEmailProcessor extends DynamicProcessorParent {
  /* Concrete class */
}

If the abstract parent classes contain abstract methods, they don't need to be implemented in either of the dynamic parent classes.

If you're working on a large project, you probably don't want to use DynamicParent as the class name unless the classes are namespaced . You'll need something more specific to avoid collisions .

Related