The Note You're Voting On
Amaroq ¶ 15 years ago
When using references in a class, you can reference $this-> variables.
<?php
class reftest
{
public $a = 1;
public $c = 1;
public function reftest()
{
$b =& $this->a;
$b = 2;
}
public function reftest2()
{
$d =& $this->c;
$d++;
}
}
$reference = new reftest();
$reference->reftest();
$reference->reftest2();
echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
However, this doesn't appear to be completely trustworthy. In some cases, it can act strangely.
<?php
class reftest
{
public $a = 1;
public $c = 1;
public function reftest()
{
$b =& $this->a;
$b++;
}
public function reftest2()
{
$d =& $this->c;
$d++;
}
}
$reference = new reftest();
$reference->reftest();
$reference->reftest2();
echo $reference->a; //Echoes 3.
echo $reference->c; //Echoes 2.
?>
In this second code block, I've changed reftest() so that $b increments instead of just gets changed to 2. Somehow, it winds up equaling 3 instead of 2 as it should.