Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Simple question, is it possible to dynamically add traits to a php class in runtime without using eval?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

As Glavic said, you can't without using eval() or reflection hacks (and I'm not even sure about that).

But it's very unlikely you really need to.

You can achieve a lot with dynamic class composition (composing a class with some functionality you want into another class). That's simply a matter of putting a reference to the class with the desired functionality into a variable in the hosting class.

class SomeClassWithNeededFunctionality {}

class SomeClassThatNeedsTheFunctionalityOfTheOtherClass {
    private $serviceClass = NULL;

    public function __construct (SomeClassWithNeededFunctionality $serviceClass) {
        $this -> serviceClass = $serviceClass;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...