Reputation: 5841
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:
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
Upvotes: 2
Views: 6174
Reputation: 2240
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;
Upvotes: 3