Reputation:
Is it possible to declare a class and have it extend a variable?
class Child extends $parentClass {}
Upvotes: 4
Views: 2848
Reputation: 473
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 {}
Upvotes: 1
Reputation: 1125
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.
Upvotes: 2
Reputation: 4880
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.
Upvotes: 0
Reputation: 704
A Class can not extend from a variable , You need to wrap the variable inside a class to extend . Hope this helps
Upvotes: 0