Simple question, is it possible to dynamically add traits to a php class in runtime without using eval?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
}
}
回答2:
No.
p.s. you can have them in standalone files, and use include() ?