'PHP Class Extends a string variable
Is it possible to declare a class and have it extend a variable?
class Child extends $parentClass {}
Solution 1:[1]
Yes, it is with eval. But it is not recommended.
<?php
function dynamic_class_name() {
if(time() % 60)
return "Class_A";
if(time() % 60 == 0)
return "Class_B";
}
eval(
"class MyRealClass extends " . dynamic_class_name() . " {" .
# some code string here, possibly read from a file
. "}"
);
?>
Is Eval an evil?! Read this.
Solution 2:[2]
A Class can not extend from a variable , You need to wrap the variable inside a class to extend . Hope this helps
Solution 3:[3]
I know this is an old question, but I hope my answer helps someone.
You can use class_alias() to an "intermediate" class:
class_alias($parentClass, 'ParentClassAlias');
class Child extends ParentClassAlias {}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | |
| Solution 3 | Stocki |
