Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend a class dynamically?

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?

like image 373
Spot Avatar asked Oct 08 '09 18:10

Spot


2 Answers

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 {} ?> 
like image 120
JacopKane Avatar answered Sep 21 '22 23:09

JacopKane


Yes. I like the answer with eval, but a lot of people afraid of any eval in their code, so here's one with no eval:

<?php //MyClass.php  namespace my\namespace; function get_dynamic_parent() {     return 'any\other\namespace\ExtendedClass';// return what you need } class_alias(get_dynamic_parent(), 'my\namespace\DynamicParent');  class MyClass extends DynamicParent {} 
like image 40
Pavel Bariev Avatar answered Sep 19 '22 23:09

Pavel Bariev