If I make a copy of a reference variable. Is the new variable a pointer or does it hold the value of the variable the pointer was referring to?
Asked
Active
Viewed 1.7k times
10
-
References are not pointers. See http://php.net/manual/en/language.references.arent.php – Artefacto May 15 '10 at 13:06
-
Sometimes you must use them, for instance when implementing offsetget. Though no doubt that references in PHP are a mess. – Artefacto May 15 '10 at 13:49
3 Answers
8
Let's make a quick test:
<?php
$base = 'hello';
$ref =& $base;
$copy = $ref;
$copy = 'world';
echo $base;
Output is hello
, therefore $copy
isn't a reference to %base
.

Crozin
- 43,890
- 13
- 88
- 135
-
2Which should be expected - the point of `$ref` being a reference to `$base` is that `$copy = $ref` should have the exact same effect as `$copy = $base`. – Tgr May 15 '10 at 13:06
-
This made me understand references far better. For some reason i though that to copy a reference you could `$copy = $ref;`. Now i understand that is like a dereference and copies the data that the reference references. I think using C pointers makes this confusing as you have to dereference manually. – Lightbulb1 Jul 02 '14 at 13:46
-
@Lightbulb1: That's because PHP's references are more like C++ references than C/C++ pointers. ;) – Crozin Jul 02 '14 at 14:22
-
Pointers and references are very confusing. I think i'm getting there haha – Lightbulb1 Jul 02 '14 at 15:14
8
It holds the value. If you wanted to point, use the &
operator to copy another reference:
$a = 'test';
$b = &$a;
$c = &$b;

AlexSp3
- 2,201
- 2
- 7
- 24

Delan Azabani
- 79,602
- 28
- 170
- 210
-
1Don't say "point". he'll think there's some difference between $a, $b and $c (like a pointer and a pointed). – Artefacto May 15 '10 at 13:51
-1
Let me murk the water with this example:
$a = array (1,2,3,4);
foreach ($a as &$v) {
}
print_r($a);
foreach ($a as $v) {
echo $v.PHP_EOL;
}
print_r($a);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
1
2
3
3
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 3
)

SubjectX
- 836
- 2
- 9
- 33
-
1Your example is **intentionally confusing**. after `foreach ($anything as &$v) {}` variable `$v` will hold the reference to last array element (while this is confusing, it's correct behavior), you should either `unset($v)` or keep in mind that `$v` is a reference. **Pro-tip: use var_dump() instead of print_r(), it will show &references in arrays** – Sanya_Zol Feb 18 '17 at 20:36