“__class 魔法方法” (通过自定义代码调节对类名的引用)
您可以使用 __get、__call 将调用重定向到某些属性/函数。
有没有办法在课堂上做到这一点?
我想将代码中所有提到的 some_class_name 转换为 MY_VERSION_some_class_name (不仅适用于一个类,它是一种模式)。
如果方法/属性是此重命名策略的目标,这将很容易。
你能想出一种方法来为 PHP 中的类做到这一点吗?
编辑:我需要这个来引用不同情况下类的不同变体。我需要将一个类名解析为该类的不同变体,具体取决于运行时已知的条件,并在整个会话中持续存在。
谢谢
如果您好奇我为什么要这样做,请查看 维护应用程序的变体
You can redirect calls to some properties/functions by using __get, __call.
Is there a way to do it for classes?
I would like to convert all mentions of some_class_name in the code to, MY_VERSION_some_class_name (not only for one class, it's a pattern).
This would be easy if methods / properties were the target of this renaming policy.
Can you think of a way to do it for classes in PHP?
Edit: I need this for referencing to different variants of classes in different situations. I need one class name to be resolved to different variants of this class, depending on a condition known at runtime, and persistent through the whole session.
Thanks
p.s.
If you are curious why I want to do this, look at Maintaining variants of an application
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法将代码中所有提及 some_class_name 的内容转换为另一个类。但是,您可以使用变量作为类名:
您所要做的就是更改变量,然后您将使用不同的类。如果您必须对很多类执行此操作,您可能需要为其创建某种工厂。
基本上,System 类将根据特定运行时需要使用的类返回不同的对象。
You can't convert all mentions of some_class_name in the code to another class. However, you can use variables as class names:
All you have to do is change the variable and you will be using a different class. If you have to do this for a lot of classes, you might want to create some sort of factory for it.
Basically, the System class would return a different object based on what class needed to be used for that particular run time.
Aiden 未经测试的方法:变量变量并生成字符串:
只要调用
getDogClass()
返回范围内变量名称的字符串,就可以了。输出为
woof
。这意味着您需要的唯一重构是查找/替换该调用中出现的类名。
但这是严峻的。而且可能很慢。此外,维护/错误跟踪噩梦类型的黑客攻击。
Aiden's untested approach: variable variables and generating a string:
As long as the call to
getDogClass()
returns a string of the name of a variable in scope then you are good.The output is
woof
.This means the only refactoring you need is to find/replace occurences of the class name with that call.
But this is grim. and probably slow. Also, a maintenance/bug-tracking nightmare type of hack.
您想要的神奇功能是
__autoload
:在此处阅读更多信息: http://php.net/manual/en/language.oop5.autoload.php
The magic function you want is
__autoload
:Read more here: http://php.net/manual/en/language.oop5.autoload.php