views:

150

answers:

3

I have been reading the PHP manual about references and something is confusing me. It says that references are not pointers to memory addresses but rather...

Instead, they are symbol table aliases.

Isn't this essentially a pointer if the reference points to the symbol table entry which then points to a memory address?

Edit:

Some great answers. Just want to pop this in here... How would I unset the variable for which another is pointing to?

$var = "text";
$ref =& $var;
unset($ref);

It looks like for this to work, I need to unset $var as well so the GC removes it.

+4  A: 

The point is that you can't do aritchmetic operations on the "pointer" as you can in some other languages, for example C. In those other languages you can do something like "pointer++" and thus go one step forward in the memory. This is not possible in PHP.

Emil Vikström
More detail: http://us.php.net/manual/en/language.references.arent.php
Brian McKenna
+1  A: 

There is a wonderful PHP References Tutorial which should explain everything in a more in depth manner than the PHP docs themselves (gasp), even going so far as to explain what happens upon variable creation.

PHP internally implements variable values through a structure know as a _zval_struct, generally referred to simply as a zval. In addition to storing the value and information about its type, the zval also specifies a refcount. The refcount counts the number of references to the value and is essential to the operation of the garbage collector, allowing memory to be freed when it is no longer in use.

A reference in PHP is simply a variable corresponding to the same zval as another variable. References can be explicitly created using a special form of the assignment operate with an ampersand after the equals sign.

cballou
Accepted because of great link. All brilliant answers though! Thanks :)
Louis
+2  A: 

It is not possible to unset a variable via a reference because unset() actually removes the reference, not the value. The garbage collector then cleans up every variable that doesn't have any references on it including the original variable name.

And this is a good thing. Imagine two objects holding references to a third one in private variables. If one object unsets it's private variable, the other one will be unaffected.

It would violate the public/private model if you could unset via references.

Techpriester