2

我不确定这在 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

4

1 回答 1

3

PHP 文档提供了一个解决方案:Returning References

<?php
class foo {
    protected $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;
于 2011-02-15T13:39:05.460 回答