tags:

views:

98

answers:

4

How do I get the PHP reference ID, as is possible with the var_dump function:

// PHP 5.2.6
class Test {}

$test1 = new Test; var_dump($test1);
$test1b = $test1;  var_dump($test1b);
$test2 = new Test; var_dump($test2);

Resulting in:

object(Test)#1 (0) {}
object(Test)#1 (0) {}
object(Test)#2 (0) {}


See, var_dump can tell which references are equal without a straight-up comparison, and it prints their reference ID #1 and #2. How do I access that reference ID?

+4  A: 

I suppose a solution could be to use spl_object_hash :

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects or for identifying an object.

It's not a "simple" number like what you get with var_dump, but I suppose it's better than nothing...


For instance, with this portion of code, inspired from yours :

$test1 = new Test;
$test1b = $test1;
$test2 = new Test;

echo spl_object_hash($test1) . '<br />';
echo spl_object_hash($test1b) . '<br />';
echo spl_object_hash($test2) . '<br />';

I get this output :

000000002c836d1d000000006bfbdc77
000000002c836d1d000000006bfbdc77
000000002c836d1e000000006bfbdc77
Pascal MARTIN
A: 

Not entirely sure if you only want to get the reference id to compare 2 instances and make sure they're equal. Should that be the case, you can use the '===' operator.

$test1 === $test1b will be true whereas $test1 === $test2 will be false.
Maurice Kherlakian
+1  A: 

I'm not proud, but this works:

ob_start();                                                                                                                                   
var_dump($test2);                                                                                                                             
$str = ob_get_contents();                                                                                                                     
ob_end_clean();                                                                                                                               

echo substr($str, strrpos($str, '#')+1, 1);
Mr-sk
I like Pascal MARTIN's answer - nice idea.
Mr-sk
A: 

Why do you want the "reference ID"? The reason I ask is that I don't think the #1 is referring to an ID, but instead telling you that this is the second instance of the object.

Can you expand on what you are trying to do that requires you to know the ID?