Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Class Extends a string variable

Tags:

php

class

Is it possible to declare a class and have it extend a variable?

class Child extends $parentClass {}

1 Answers

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.

like image 112
Erfun Avatar answered Oct 21 '25 01:10

Erfun