PHP runtime class modification

后端 未结 3 390
猫巷女王i
猫巷女王i 2020-12-09 22:17

So I want to be able to add/remove class methods at runtime. Before you tell me that\'s horrible pratice in oop, it might be, but I don\'t really care. The reason I want to

3条回答
  •  粉色の甜心
    2020-12-09 22:23

    RunKit extension can do it (runkit_method_add(), etc.)

    However it's an experimental extension and you're already aiming at your foot...

    You have other options:

    • Emulate new fields and methods with __get() and __call()
    • Use subclassing and Factory pattern (class Plugin extends BaseImplementation and have factory instantiate Plugin instead of BaseImplementation). Zend Plugin Loader does something like this.
      It's the solution with least overhead, but also is limited to one plugin extending one class.
    • Add hooks and use delegation (Strategy pattern) ($this->plugin->onFoo()). There's library for this.

提交回复
热议问题