Page 1 of 1

Object identity check

Posted: Mon Sep 18, 2006 2:26 pm
by Luke
How do you test whether two variable are referencing the same object? I have two instances of $db, and I'm not sure whether they reference the same object... how can I check?

Posted: Mon Sep 18, 2006 2:32 pm
by volka
In php5 you can use ===

Code: Select all

<?php
class foobar {
	private $xyz;
	
	public function __construct($xyz) {
		$this->xyz = $xyz;
	}
}

$f1 = new foobar(1);
$f2 = $f1;
$f3 = clone $f1;
$f4 = new foobar(4);


echo '$f1===$f2: ', $f1===$f2 ? 'true':'false', "<br />\n";
echo '$f1===$f3: ', $f1===$f3 ? 'true':'false', "<br />\n";
echo '$f1===$f4: ', $f1===$f4 ? 'true':'false', "<br />\n";
?>

Posted: Mon Sep 18, 2006 2:55 pm
by Luke
nice... thanks!

I am using php5, so that will work, but let's say, just for the sake of argument, that I'm using php4... then how would I do it?

Posted: Mon Sep 18, 2006 3:04 pm
by feyd
Inject a property into it on one, check if it's there in the other. If they are, they are references to the same objects, otherwise you've got other things.

Take a look at SimpleTests assertReference() method.