PHP class Extends string variable
3 answers
no, you cannot.
this is because in the normal definition:
class A extends SomeOtherClass {
}
SomeOtherClass is a namespace reference, not a class instance. And you cannot use a variable to enforce that namespace, because variables in PHP are defined at runtime, whereas classes are defined at compile time.
But ... if you are using PHP7 you can do this:
$newClass = new class extends SomeOtherClass {};
which is not exactly what you want, but goes somehow.
0
source to share
Yes, this is with eval. But this 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 Evil ?! Read this .
+1
source to share