Question

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

Was it helpful?

Solution

The PHP documentation provides a solution: 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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top