Object identity check

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Object identity check

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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";
?>
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply