Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
Thread: Dynamic class extending.
11-16-2006, 05:30 PM #1
- Join Date
- Aug 2003
- One step ahead of you.
- Thanked 3 Times in 3 Posts
Dynamic class extending.
I had this idea to check if it wouldn't be possible to, somehow, be able to extend a class dynamically. It turns out it is.
I've written two classes that allow you to do this. It is a sort of hack but it works astonishingly well.
To make it work you just have to extend your class by the "dynamic_extend" class and tell it which classes you'd like to have as children.
class my_extend-able_class extends dynamic_extend
protected $property = 'Set by parent';
$foo = $this->function_in_child_class();
// and so on...
$c = new my_extend-able_class;
// and so forth...
The class that will become a child of the extend-able class should be extended by it, but it is not required.
class child_class extends dynamic_parent
$this->property = 'Set by dynamic child!';
This hack does have some limitations:
- method_exists()/property_exists() will return a wrong value. To overcome this "dynamic_extend" has methods (has_method()/has_property()) that will return the correct answer. Some other functions may give false results as well.
- Constants are currently not passed. This can be done though.
- Interface will not be inherited. There is no way to fix this though it is not really needed for dynamically added children.
- No errors are given even if invalid actions are made (requesting a protected method from outside class for example). This can be arranged
- The reflection API won't see the child elements. This could be fixed by extending some reflection classes.
- Children can't overload anything. This can probably be fixed.
I don't recommend anyone to start using it unless they're sure what they're doing. It's more of nice thing to check out.
$parent = new parent_class();
$parent->foo = ' World';
Last edited by marek_mar; 11-16-2006 at 05:32 PM.I'm not sure if this was any help, but I hope it didn't make you stupider.
Experience is something you get just after you really need it.
PHP Installation Guide Feedback welcome.