Variable variable class extensions in PHP--is it p

2020-02-01 05:24发布

Is something like the following possible in PHP?

$blah = 'foo1';

class foo2 extends $blah {
    //...
}

class foo1 {
    //...
}

This gives an error.

I want to dynamically set $blah so I can extend whatever class I want.

Edit: The reason for wanting to do this because I wanted to use a function out of another class in a related class. In the end it would have been something like:

Final extends foo1 extends foo2 extends foo3 extends foo4 extends parent { ... }

In the end I decided to instantiate the other class within the class and use it. Not the best options because they both you 2 of the same classes, but this won't be used that often, so it will work for now.

8条回答
来,给爷笑一个
2楼-- · 2020-02-01 05:52

I know this question was asked a long time ago, but the answer is relatively simple.

Assuming you want to extend class foo if class foo exists, or class bar if it doesn't, you'd use:

if(!class_exists('foo')) {
    class foo extends bar {
        function __construct() {
            parent::__construct();
        }
    }
}

class myclass extends foo{
    //YOUR CLASS HERE
}
查看更多
看我几分像从前
3楼-- · 2020-02-01 05:55

I assume that this is for ease-of-maintenance, right? Extending a class at run time really is pretty crazy.

class SuperClassOne { /* code */ }
class SuperClassTwo { /* code */ }

class IntermediateClass extends SuperClassOne { /* empty! */ }

class DescendantClassFoo extends IntermediateClass{ }
class DescendantClassBar extends IntermediateClass{ }
class DescendantClassBaz extends IntermediateClass{ }

Then, when you want to change all your DescendantClass* classes, you just have to change what the IntermediateClass extends:

class IntermediateClass extends SuperClassTwo { }
查看更多
登录 后发表回答