PHP runtime class modification

后端 未结 3 389
猫巷女王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:21

    You can override the class, but I don't know if you can reload it in the same request. some behavior change can be achieved with mediator design pattern (symfony event dispatcher) but you need to know the extension points in advance, and fire events/messages to be caught by an extending class in the future..

    if you can wait for the next request, and clear cache if you have it. I made a tool that might help you. SourceEditor

    Here there are more answers to a similar question too, where I put code examples. How to generate or modify a PHP class at runtime?

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-09 22:40

    PHP doesn't allow this. It may be a dynamic language in other respects, but the class system is deliberately restrictive. You can either install the runkit extension, which changes the language to allow mocking about with classes at runtime (But then you aren't using plain PHP anymore), or you can use the magic-methods to simulate it.

    0 讨论(0)
提交回复
热议问题