如何在类定义(而不是对象实例化)上运行代码
我正在寻找一种在定义类时透明地运行代码的方法 - 更重要的是,在扩展类时。
例如,如果我有:
class A
{ function define()
{ echo "A has been defined!\n";
}
__magicDefine
{ define();
}
}
class B extends A
{
}
我希望打印“A 已被定义!\n”。 这不可能吗?
I'm looking for a way to transparently run code when a class is defined - more importantly, when the class is extended.
For example, if I have:
class A
{ function define()
{ echo "A has been defined!\n";
}
__magicDefine
{ define();
}
}
class B extends A
{
}
I'd like that to print "A has been defined!\n". Is this impossible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Java 中,这是可能的,通过使用“java 代理”,它会向 JVM 注册
java.lang.instrument.ClassFileTransformer
。In Java, this is possible, by using a "java agent" which would register a
java.lang.instrument.ClassFileTransformer
with the JVM.那是不可能的,是的。 类定义中没有任何内容被调用。
这个概念甚至根本不被支持。 尝试编写
,你会得到
致命错误:构造函数 blah::__construct() 不能是静态的
。That would be impossible, yeah. Nothing gets called on class definition.
This concept is even sort of aggressively unsupported; try writing
and you'll get
Fatal error: Constructor blah::__construct() cannot be static
.我猜你想要做的是跟踪正在运行的对象? 不太确定您的最终目标是什么。
也许您正在运行时寻找 ReflectionClass? 您可以确定某个类是否存在以及扩展类是什么。
听起来您的目标也是一个跟踪正在使用的对象的对象工厂。 查找这些概念的单例、工厂和静态成员函数/变量概念。
至于这一点:
如果类 B 重写了构造函数,它就不会调用 A 的构造函数。 例如:
但是在代码中,您可以通过多种方式之一检查 B 是否是 A 的实例:
不知道这是否有很大帮助。
I guess what you're trying to do is keep track of objects that are running? Not exactly sure what your end goal is here.
Perhaps you're looking for the ReflectionClass at run time? You can determine if a class exists and what the extended class is.
It also sounds like what you're aiming for is an object factory that keeps track of objects that are being used. Look up singletons, factory, and static member functions/variables concepts for those.
As for this:
if class B overrides the constructor, it's not going to call A's constructor. Ex:
However in code, you can check if B is an instance of A one of many ways:
Don't know if that helps much.