PHP class Extends string variable

Is it possible to declare a class and extend it?

class Child extends $parentClass {}

      

+3


source to share


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


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


The class cannot propagate to the variable, you need to wrap the variable inside the extendable class. Hope it helps

0


source







All Articles