Adapted from this
PHP's strictest comparison operators still only go as far as indicating whether two variables have the same value but what if you want to be sure one variable is a reference to another, not just a container for a matching value?
PHP has no built in way to do this as of now but you can work around this by doing a test of your own. If you have this:
$a = 'a';
$b =& $a;
$b = "changed";
if ($a==='changed') echo '$a is a reference to $b'."\n";
else echo '$a is a not reference to $b'."\n";
Of course if $a
was originally "changed"
this test is meaningless. Also, it modified our variable to do the test which we probably don't want. We can store a temporary variable to correct this.
$t = $a; # temporary backup of value
$bool = ($a = "changed") === $b;
$a = $t; # restore from backup value;
We can do a test to decide what to change $a
to, ensuring we aren't changing it to something it already is using the ternary operator. We'll set it to 1
or 0
$t = $a; # temporary backup of value
$bool = ($a = $a===0 ? 1 : 0) === $b;
$a = $t; # restore from backup value;
Here is is in a function for re-use:
function is_ref_to(&$a, &$b) {
$t = $a; # temporary backup of value
$bool = ($a = $a===0 ? 1 : 0) === $b;
$a = $t; # restore from backup value;
return $bool;
}