dongyang7152 2014-08-03 01:28
浏览 212

如何替换已加载的类?

I have a system that uses an auto loader to load a class. I am able to edit the auto loader, but I want people to be able to extend one of my classes and have my system still run.

Lets say class A is the original and class B is the new one that extends class A.

I have:

A.php
namespace Core;
class A{}

B.php
namespace Core;
class B extends OverriddenA{} ( Explained below )

When the autoloader loads A - instead of actually loading A, I want it to load B, which requires the real A to be loaded. So it should look like this:

include 'A.php';
class_alias('A', 'OverriddenA');
include 'B.php';
class_alias('B', 'A');

The problem is that the second class_alias() errors because A is already loaded as A.

Presently the only solution I can think of is to do a file_read_contents(), replace the class name and run an eval() - but I would really hate to do that.

  • 写回答

1条回答 默认 最新

  • dpjjr42626 2014-08-03 01:57
    关注

    Ok I found a great way to do this.

    The class that the system will look for is Core\A

    So that file is actually created as Overridable\A

    When it's loaded, the class loader sees that it's overridable so it looks if it's overridden. If it is, it loads the override which already declares itself as Core\A extends Overridable\A

    If there is no override, but it's in the Overridable namespace, it creates an alias: class_alias(Overridable\A, Core\A);

    And just so my IDE can still be able to reference everything, I create a file called Overrides.php which is never actually included that just says:

    namespace: Core;
    class A overrides \Overridable\A {}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂