4

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

class Child extends $parentClass {}

4 Answers4

2

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.

Community
  • 1
  • 1
Erfun
  • 1,079
  • 2
  • 11
  • 26
0

no you cant.

this is because in a normal definition:

class A extends SomeOtherClass {
}

SomeOtherClass is a namespace reference, not an instance of the class. And you cant use a variable to provide that namespace because variables in PHP are defined at runtime, whereas classes are defined in the compile phase.

But... if youre using PHP7, you can do this:

$newClass = new class extends SomeOtherClass {};

which is not exactly what you want, but goes some way.

DevDonkey
  • 4,835
  • 2
  • 27
  • 41
0

A Class can not extend from a variable , You need to wrap the variable inside a class to extend . Hope this helps

Maaz Rehman
  • 674
  • 1
  • 7
  • 20
0

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 {}
Stocki
  • 463
  • 4
  • 14