is it possible to add traits to a class in PHP in runtime?

后端 未结 2 935
清酒与你
清酒与你 2020-12-17 10:05

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

相关标签:
2条回答
  • 2020-12-17 10:23

    No.

    p.s. you can have them in standalone files, and use include() ?

    0 讨论(0)
  • 2020-12-17 10:36

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题