0
class ClassOne 
{
    private $foo = null;

    public function __construct() 
    {
        $this->foo = new ClassTwo();
    }

    public function doStuff() 
    {
        $bar = &$this->foo->someVariable;
    }
}

I know that $this refers to the current object, and & is a reference symbol for changing the original variable.

What is &$this referring to?

localheinz
  • 9,179
  • 2
  • 33
  • 44
mooncoder
  • 81
  • 2
  • 3
  • 1
    if `$bar = &$foo` makes sense to you, why would `$bar = &$this` be any different? – zzzzBov Aug 18 '17 at 22:52
  • 7
    Note that the `&` applies to everything at the right of it, so it gives a reference to `$this->foo->someMethod`, not `$this`. – trincot Aug 18 '17 at 22:53
  • What are you trying to accomplish? You are storing a reference to `$this->foo->someMethod` in `$bar` and I wonder what you are not understanding about that. – k0pernikus Aug 18 '17 at 22:55
  • And that's not pass-by-reference that is assigning a reference. – AbraCadaver Aug 18 '17 at 23:27
  • thanks @k0pernikus. It was actually "someVariable" not "someMethod" Why would a reference like this ever be needed? I'm trying to understand some old code someone wrote back in 2004. – mooncoder Aug 18 '17 at 23:27
  • 1
    I think you may have removed too much when creating your generic example here for us to really see why it does it that way. – Don't Panic Aug 18 '17 at 23:41

1 Answers1

0

Thanks to @k0pernikus and @trincot for clarifying that & refers to the entire $this->foo->someVariable

So the original author wanted to change someVariable in $this->foo->someVariable. Since it was verbose, he assigned the reference to $bar.

However, this was done in PHP4. There must be a better way to write this in PHP5.

mooncoder
  • 81
  • 2
  • 3
  • If `$someVariable` holds an object then the reference is not needed (and not even useful). Otherwise, there is no better way to write it in PHP 5 or PHP 7. – axiac Aug 19 '17 at 00:05