user439441
user439441

Reputation:

PHP Class Extends a string variable

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

class Child extends $parentClass {}

Upvotes: 4

Views: 2848

Answers (4)

Stocki
Stocki

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

Erfun
Erfun

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

DevDonkey
DevDonkey

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

Maaz Rehman
Maaz Rehman

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

Related Questions