PHP 对静态变量的引用
我不确定这在 PHP 中是否可行,但这就是我尝试做的。我的类中有一个静态变量,我想将其作为类外的引用。
class Foo {
protected static $bar=123;
function GetReference() {
return self::&$bar; // I want to return a reference to the static member variable.
}
function Magic() {
self::$bar = "Magic";
}
}
$Inst = new Foo;
$Ref = $Inst->GetReference();
print $Ref; // Prints 123
$Inst->DoMagic();
print $Ref; // Prints 'Magic'
有人可以确认这是否可能或有其他解决方案来实现相同的结果:
- 变量必须是静态的,因为类 Foo 是基类,并且所有派生类都需要访问相同的数据。
- HTML 需要访问类引用数据,但如果没有 setter 方法就无法设置它,因为类需要知道变量何时设置。
我想它总是可以通过在类之外声明的全局变量和一些编码规则作为紧急解决方案来解决。
// 谢谢
[编辑]
是的,我使用 PHP 5.3.2
I'm not sure if this is possible at all in PHP but this is what I try to do. I have a static variable in my class that I want to have as a reference outside the class.
class Foo {
protected static $bar=123;
function GetReference() {
return self::&$bar; // I want to return a reference to the static member variable.
}
function Magic() {
self::$bar = "Magic";
}
}
$Inst = new Foo;
$Ref = $Inst->GetReference();
print $Ref; // Prints 123
$Inst->DoMagic();
print $Ref; // Prints 'Magic'
Can someone confirm if this is possible at all or another solution to achieve the same result:
- The variable must be static because class Foo is a base class and all derivates needs access to the same data.
- HTML needs access to the class reference data, but not to be able to set it without a setter method because the class needs to know when the variable is set.
I guess it can always be solved with globals declared outside the class and some coding disciplines as an emergency solution.
// Thanks
[EDIT]
Yes, I use PHP 5.3.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PHP文档提供了一个解决方案:返回引用
The PHP documentation provides a solution: Returning References