PHP dynamic class extending
Question by tim
I know you can extend a class when constructing it like the following:
class b extends a {
}
But is it possible to dynamically extend classes from the scripts? Such as:
$b = new b($input) extends a;
What I wish to accomplish is to extend the module differnetly wheither it’s used in admin rather than the public pages. I know I can create two different parent classes by the same name and only include one per admin or public. But my question is, is it possible to do it dynamically in PHP?
Answer by Cory Carson
You can’t, but this has been requested for a few years: https://bugs.php.net/bug.php?id=41856&edit=1
You can define the classes within an eval, but it’s more trouble than declaring the class normally.
Answer by Starx
Yes, as cory mentioned, this feature has been requested before. But before that, you can create a workaround. Here is my old school trick for this
Create two separate classes like these:
class a {
}
class b {
public $object;
}
Then, create an extended version too
class bextendeda extends a {
}
In the constructor method of class b, place few functions which redirects to the extended object if requested.
class b {
public $object;
public function __contruct($extend = false) {
if($extend) $this -> object = new bextendeda();
else $this -> object = $this;
}
function __get($prop) {
return $this-> object -> $prop;
}
function __set($prop, $val) {
$this-> object -> $prop = $val;
}
function __call($name, $arguments)
{
return call_user_func_array($this -> object, $arguments);
}
}
And there you have it, IF you want the extended version just do this
$b = new b(true);
If not
$b = new b();
Enjoy 🙂