如何在类中声明公共变量变量
嘿,我有一个这样的类
class derp{
public $$ini;
public static function regIni($ini){
derp::$$ini = 'test';
}
}
然后在另一个文件中我有
core::regIni('register');
然后在其他地方我使用
core::$register;
这会产生一个错误
public $$ini
不是有效的代码但如果我不保留它我无法设置
core::$$ini
如何解决这个问题?
请注意,$$ini 是一个变量,这意味着 $ini 的值实际上是变量名称,因此 $ini = 'registry' 那么 $$ini 实际上意味着 $registry。
Hey I have a class like this
class derp{
public $ini;
public static function regIni($ini){
derp::$ini = 'test';
}
}
And then in another file I have
core::regIni('register');
And then somewhere else I use
core::$register;
This produces an error
public $ini
is not valid code but if I leave it without I can not set
core::$ini
How do I fix this?
Please note that $$ini is a variable variable meaning the value of $ini is actuely the variable name so $ini = 'registry' then $$ini actualy means $registry.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不使用访问方法来设置和获取类数据?
Why not use access methods for setting and getting class data?
所以,这不是一个非常有帮助的答案,因为我只能得出结论,目前这是不可能的。
new ReflectionProperty("derp", "static_prop")
并将其附加。这确实只是为了内省。$c = new ReflectionClass("derp");
和$derp->setStaticPropertyValue("p", 123);
也不起作用。属性仍然需要预定义。runkit_*
函数也无法帮助完成此任务。它们主要用于改变方法。我不知道其他此类 PECL 扩展,但无论如何,这作为一般解决方案都没有用处。因此,对于当前的 PHP 版本,您无法在解析阶段之后添加静态类属性。
So, this is not an overly helpful answer, as I can just conclude that it's currently not possible.
new ReflectionProperty("derp", "static_prop")
for example and attach it. It's really for introspection only.$c = new ReflectionClass("derp");
and$derp->setStaticPropertyValue("p", 123);
is not working either. The properties need to be predefined still.runkit_*
functions help with this task. They are intended for changing methods mainly.I'm not aware of other such PECL extensions, but that wouldn't be useful as general solution anyway. So for current PHP versions you cannot add static class properties after the parsing stage.
看一下魔术方法 __set 和 __get
take a look at magic methods __set and __get
马里奥说:
Geuss,我会解决这个问题。
创建一个数组 $ini 并将值加载到那里 derp:$ini['base']['key']
感谢您的帮助,
Robin
Mario said:
Geuss i'l settle for a work around then.
Made an array $ini and loaded the values into there derp:$ini['base']['key']
Thanks for the help,
Robin