简体   繁体   中英

Change parent class depend on variable

How can i set parent class depend on some statement?

Example

$switcher = true;

if($switcher) {
 class a extends class1{
 ...
}
else {
 class a extends class2 {
 ...
}

i need something like this

$myclass = $switcher ? 'class1' : 'class2';

class a extends $myclass { //sure this will not work

But how to use $myclass without eval

Thanks

Classes are parsed at compile time, not runtime, so in effect you cannot . Consider instead creating 2 classes with different parents and instantiating them dynamically according to your $switcher . It doesn't make much sense to try to change an inheritance hierarchy at runtime.

Your intended approach seems to be crying out for rethinking the architecture. If class1 and class2 are distinct classes, then they by definition should not have much in common to be interchangeable to downstream child classes, and if they do have a lot in common, it may point to a problem higher in the inheritance heirarchy, where one might perhaps need to inherit from the other.

The common sense approach would be the one of declaring two classes, let's call them A1 and A2 , one extending Class1 , the other extending Class2 . Then, you decide which one you want to instantiate.

However you can't do exactly what you want it without eval . PHP supports anonymous functions and closures, but doesn't support anonymous classes.

You can do it like this:

class MyCommon {}
class MyClassA extends MyCommon {}
class MyClassB extends MyCommon {}

$switcher = true;

if ($switcher) {
    $myinstance = new MyClassA();
} else {
    $myinstance = new MyClassB();
}

var_dump($myinstance instanceof MyCommon); // true, because of inheritance
var_dump($myinstance instanceof MyClassA); // true
var_dump($myinstance instanceof MyClassB); // false
var_dump(get_class($myinstance)); // "MyClassA"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM