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

2
  • What is your target PHP version? Commented Feb 15, 2011 at 13:33
  • 1
    Why make a reference? In most cases it can be handled without a reference (for example, using explicit getters/setters). References make code which is rather difficult to debug (since side-effects in one piece of code can effect other pieces of code). Try to stay away from them unless absolutely necessary (which in my experience is seldom)... Commented Feb 15, 2011 at 13:44

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

4 Comments

if you make $value public, you can directly access that outside from the class
+1v It works!!! I'm an old fashion C++ OOP, so I kept it protected :) I was googling high and low and never came across this. Well, guess I have to improve my search technique as well :D Thank you!
ajreal that's correct. I updated the example. Now, it makes more sense.
I don't always need to lookup how to reference object variables, but when I do, i'm using PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.