PHP:在运行时向类添加常量
我有以下代码:
interface ITest {
const SIGNAL_FOO = 'foo';
}
class SomeClass extends SignalSlotObject implements ITest {
const SIGNAL_BAR = 'bar';
}
SignalSlotObject
在运行时从类及其实现的所有接口中获取以“SIGNAL_”开头的所有常量。这很好并且有效,但我的问题是:
$c = new SomeClass();
$c->connect(SomeClass::SIGNAL_BAR, ...); //works well
$c->connect(ITest::SIGNAL_FOO, ...); //also works well
$c->connect(SomeClass::SIGNAL_FOO, ...); //doesn't work
如果让第三个选项也能工作那就太好了,因为使用 SomeClass
的程序员无法知道这个信号是否在 SomeClass< 中定义。 /code> 或其接口之一。
我的目的是在运行时将接口中定义的常量动态添加到类中,但我不知道如何在运行时将常量添加到类中。我也无法使用 __set
和 __get
因为它们不适用于静态范围(它们适用于 $c->SIGNAL_FOO
但不适用于对于 SomeClass::SIGNAL_FOO
)。
i have the following code:
interface ITest {
const SIGNAL_FOO = 'foo';
}
class SomeClass extends SignalSlotObject implements ITest {
const SIGNAL_BAR = 'bar';
}
SignalSlotObject
fetches all constants beginning with 'SIGNAL_' at runtime from the class and from all interfaces it implements. That's fine and works, but my problem is:
$c = new SomeClass();
$c->connect(SomeClass::SIGNAL_BAR, ...); //works well
$c->connect(ITest::SIGNAL_FOO, ...); //also works well
$c->connect(SomeClass::SIGNAL_FOO, ...); //doesn't work
It would be great to let the 3rd option work as well because the programmer using SomeClass
can't know, if this signal is defined in SomeClass
or one of it's interfaces.
My intention was to dynamically add the constants defined in the interfaces to the class on runtime but I have no hint how to add a constant on runtime to a class. I also cannot use __set
and __get
because they do not work on a static scope (They would work for $c->SIGNAL_FOO
but not for SomeClass::SIGNAL_FOO
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论