Is it possible to dereference a reference in PHP?
<p>I have an array I'm using as a stack to store a path through a tree. Each element points to a node in the tree and I want to pop the last element off and then set the object referred to by that element to null.</p>

<p>Basically:</p>

<pre><code>$node = array_pop($path);
*$node = null;
</code></pre>

<p>assuming that PHP had a '*' operator as C-ish languages do. Right now I have the ugly solution of starting at the parent node and remembering which child I took and then setting that to null as in:</p>

<pre><code>if($goLeft) {
    $parent-&gt;left = null;
} else {
    $parent-&gt;right = null;
}
</code></pre>

<p>I say this is ugly because the array containing the path is created by a public function in my tree class. I'd like to expose the ability to work directly on the nodes in a path through the tree without exposing an implementation detail that addresses an idiosyncrasy (feature?) in PHP. ATM I need to include a boolean in the return value ($goLeft in this case) just so I can workaround an inability to dereference a reference.</p>

<p>This is the second time I've encountered this problem, so if anyone knows a way I can do something similar to the first block of code please share!</p>

<p>(EDIT)</p>

<p>After experimenting with many permutations of &amp;'s and arrays, it turns out that the basic problem was that I had misinterpreted the reason for an error I was getting.</p>

<p>I tried</p>

<pre><code>$a = ($x &gt; $y) ? &amp;$foo[$bar] : $blah;
</code></pre>

<p>and got " syntax error, unexpected '&amp;' ". I interpreted this to mean that the problem was using the &amp;-operator on <code>$foo[$bar]</code>. It actually turns out that the culprit is the ?-operator, as</p>

<pre><code>if($x &gt; $y) {
    $a = &amp;$foo[$bar];
} else {
    $a = null;
}
</code></pre>

<p>works perfectly fine. I thus went on a wild goose chase looking for a workaround for a problem that didn't exist. As long as I don't break the chain of &amp;'s, PHP does what I want, which is to operate on the object referred to by a variable (not the variable itself). Example</p>

<pre><code>$a1 = new SomeClass;
$a2 = &amp;$a1;
$a3 = &amp;$a2;
$a4 = &amp;$a3;

$a4 = 42;    // This actually sets $a1 to 42
var_dump($a1); // Emits 42
</code></pre>

<p>What messed me up is that I thought objects are passed around by reference anyway (this is wrong), so I didn't think the &amp; was necessary if the expression resolved to an object. I mean:</p>

<pre><code>class A {
    public $b;
}

class B {}

$a = new A;
$a-&gt;b = new B; 

$c1 = $a-&gt;b; 
$c2 = &amp;$a-&gt;b;

$c1 = 42; // Merely assigns 42 to $c1
$c2 = 42; // Assigns 42 to $a-&gt;b
</code></pre>

<p>It turns out that this exact issue is addressed at <a href="http://www.php.net/manual/en/language.oop5.references.php" rel="nofollow">http://www.php.net/manual/en/language.oop5.references.php</a>. Wish that had sunk in the first time I read it!</p>
