Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In PHP all values are saved in so called <code>zval</code>s. Those <code>zval</code>s contain the actual data, type information and - this is important for your question - a reference count. Have a look at the following snippet:</p> <pre><code>$a = new B; // $a points to zval(new B) with refcount=1 $b = $a; // $a, $b point to zval(new B) with refcount=2 (+1) $c = $b; // $a, $b, $c point to zval(new B) with refcount=3 (+1) unset($a); // $b, $c point to zval(new B) with refcount=2 (-1) </code></pre> <p>As soon as the <code>refcount</code> reaches <code>0</code> the <code>zval</code> is freed and the object destructor is called.</p> <p>Here are some examples of the <code>refcount</code> reaching <code>0</code>:</p> <ul> <li><p><code>unset</code>ing a variable:</p> <pre><code>$a = new B; // refcount=1 unset($a); // refcount=0 =&gt; __destruct! </code></pre> <p>But:</p> <pre><code>$a = new B; // refcount=1 $b = $a; // refcount=2 unset($a); // refcount=1 =&gt; no destruct as refcount &gt; 0, even though unset() was called! </code></pre></li> <li><p>leaving function (or method) scope</p> <pre><code>function a() { $a = new B; // refcount=1 } // refcount=0 =&gt; __destruct! (as $a does not exist anymore) </code></pre></li> <li><p>script execution end</p> <pre><code>$a = new B; // refcount=1 die(); // refcount=0 =&gt; __destruct! (on script execution end all vars are freed) // doesn't need to be die(), can be just normal execution end </code></pre></li> </ul> <p>These obviously are not all conditions leading to a reduction of <code>refcount</code>, but the ones you will most commonly meet.</p> <p>Also I should mention that since PHP 5.3 circular references will be detected, too. So if object <code>$a</code> references object <code>$b</code> and <code>$b</code> references <code>$a</code> and there aren't any further references to <code>$a</code> or <code>$b</code> the <code>refcount</code>s of both will be <code>1</code>, but they still will be freed (and <code>__destruct</code>ed). In this case though the order of destruction is undefined behavior.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload