0

Is there any difference between pointers and references? When should I use references?

What actually this syntax does?

$a = &$b
Mikhail Zhuravlev
  • 969
  • 2
  • 10
  • 22

1 Answers1

1

Do not use references! They can lead to unexpected behavoiur.

As at PHP.net: One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true.

There are pointers and references, you can see it it example below.

  • $a = new stdClass ($a now is a pointer to #168)
  • $b = $a ($b is now a new pointer, but it still points to #168)
  • $c = &$a ($c is now a reference to pointer $a)
  • you can't distinguish $b from $c
  • $a = null, it's just not a pointer anymore, just null
  • #168 is kept, because there are pointers to it left
  • $b is still a pointer to #168
  • $c is now null

This behavior is dangerous, because it alters variable you don't touch.

$b === $c // returns true
$youCantSayThisVariableIsRelated = null
$b === $c // returns false!

enter image description here

Mikhail Zhuravlev
  • 969
  • 2
  • 10
  • 22