开发者

PHP Unset via References

I have been reading the PHP manua开发者_Python百科l 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.


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.


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.


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.


PHP global or $GLOBALS

From @Artefacto: "Inside a function, if you want to unset a global variable, you must use unset($GLOBALS['varname']), not global $varname; unset($varname);."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜