donk68254 2012-11-20 11:36
浏览 23

在PHP中导入用户子类

I've coded a small PHP engine which includes some abstract classes. The user of the engine must implement subclasses of these abstract classes, and supply their subclasses to the engine. The engine has to be able to create and manipulate instances of these subclasses, so the user can't just create an instance and pass it to the engine.

So I need a way for the user to pass their subclasses to the engine. One obvious way would be to force the user to give these subclasses a specific name and put them in a specific directory, but that just seems inelegant somehow. Knowing that PHP could store classes in variables, what I tried first was to store the classes in constants, so I had a file with a few defines that user would fill in with the names and paths of their subclasses. That didn't work - it would seem PHP cannot store classes in constants, only variables.

So now I'm trying the same approach, but with variables instead of constants. There's a file, UserIncludes.lib.php, in which the user is required to set two variables to the names of their subclasses. Then those variables are used to call those subclasses throughout the engine's code. I'm not sure this is a good system, particularly because of the need to import the variables into every function that needs them using the global keyword, increasing the clerical and mental load on the engine.

So what are best practices for doing this sort of thing in PHP? It seems like it must be a fairly common task.

  • 写回答

1条回答 默认 最新

  • dtpf76658 2012-11-20 11:50
    关注

    Just use namespaces, with a proper autoload function.

    This way filesystem becomes just a transparent layer, and you rely just on naming convention - which is "force the user to give these subclasses a specific name and put them in a specific directory" actually, but it works quite good.

    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据