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?
While it's still not possible and not exactly your answer i needed the same thing and didn't wanted to use eval, monkey-patching etc. So i used a default class by extending it in conditions.
Of course it means if you have 100 classes to extend you need to add 100 conditions with another extending operation but for me this looked like the right way.
<?php
if(class_exists('SolutionClass')) {
class DynamicParent extends SolutionClass {}
} else {
class DynamicParent extends DefaultSolutionClass {}
}
class ProblemChild extends DynamicParent {}
?>
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