0

Following this guide, but it is always difficult for me to understand references in PHP. What is the purpose of using reference in the params below?

public function register($name, &$object)
{
    $this->registries[$name] =& $object;
}
public function &getRegistry($name)
{
    return $this->registries[$name];
}

Without the references:

public function register($name, $object)
{
    $this->registries[$name] = $object;
}

public function getRegistry($name)
{
    return $this->registries[$name];
}

It works fine too without the the references, so what is the advantages having them?

Run
  • 54,938
  • 169
  • 450
  • 748
  • 1
    If `$object` is actually and object, then I'm not sure there is any advantage in these examples. – Jonnix Sep 06 '16 at 09:35
  • 1
    Passing by reference passes a reference to the object, not a copy of the object. If you pass by reference you can modify the object within the method and the modifications will be applied to the object passed as an argument. – rosengrenen Sep 06 '16 at 09:47
  • 1
    @Rasmus If the `$object` is *an object*, modifications will affect it either way, with or without explicit reference. Objects aren't copied on assignment. – deceze Sep 06 '16 at 09:50

1 Answers1

2

Objects needed to be explicitly passed by reference back in the PHP 4 dark ages. Since PHP 5.0 objects essentially are a reference and it doesn't make any difference whether you pass the object reference by reference or not. Every guide on the matter will tell you to omit passing objects by reference.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks for the answer! – Run Sep 06 '16 at 09:47
  • 1
    It does make a difference. If you pass and store the object as a reference then changing the value of the originally passed variable (e.g. setting it to a different object or even other type) will affect the value in `$this->registries` as well. – Shira Sep 06 '16 at 09:47
  • Yes, fair enough, if you use references then your code will behave according to the rules of references, which is often something you'll flat out want to avoid, except for very specific occasions. This isn't one of those occasions. – deceze Sep 06 '16 at 09:53