References

References at the PHP source level map fairly straightforwardly onto the internals. Consider this PHP code:

    <?php
     $a = "Hello World";
     $b =& $a;
    ?>

Here $b is a reference to the same zval container as $a. Internally in PHP, the is_ref indicator is set to 1 for both the zval containers, and the reference count is set to 2. If the user then does an unset($b), the is_ref indicator on the $a container is set to 0. The reference count actually remains at 2, since the $a symbol table entry is still referring to this zval container and the zval container itself also counts as a reference when the container is not a reference itself (indicated by the is_ref flag being on). This may be a little bit confusing, but keep reading.

When you allocate a new zval container using MAKE_STD_ZVAL( ), or if you call INIT_PZVAL( ) directly on a new container, the reference count is initialized to 1 and is_ref is set to 0. If a symbol table entry is then created for this container, the reference count becomes 2. If a second symbol table alias is created for this same container, the is_ref indicator is turned on. If a third symbol table alias is created for the container, the reference count on the container jumps to 3.

A zval container can have a reference count greater than 1 without is_ref being turned on. This is for performance reasons. Say you want to write a function that creates an n-element array and initializes each element to a given value that you provide, much like PHP’s array_fill( ...

Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.