Skip to content

Instantly share code, notes, and snippets.

@Jeff-Russ
Last active January 18, 2017 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jeff-Russ/57b714a6c8408da801d05bea020dab95 to your computer and use it in GitHub Desktop.
Save Jeff-Russ/57b714a6c8408da801d05bea020dab95 to your computer and use it in GitHub Desktop.
PHP: Test if Variable is Reference to Another

PHP Testing if Two Variables are Referring to Same Data.

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment