tags:

views:

2484

answers:

4
+7  Q: 

PHP Object ID

Hi,

I'm using PHP 5.2. I'd like to find a way to output a unique id for every object, so it's easy when looking over logs to see which objects are the same.

In Ruby, I'd just say object.object_id to get Ruby's internal identifier for the object. There doesn't seem to be an obvious way to do this in PHP.

Is there is a built-in way of doing this? If there isn't, can you offer any other suggestions?

Thanks.

A: 

I don't know how Rubys object.object_id works, does it return the class ID or an instance ID?

If you want the class "ID", you could use the class name in PHP:

<?php
$instance = new Foo();
echo get_class($instance);
?>

http://de.php.net/get_class

Sebastian Hoitz
Ruby object id is an instance id.
Ollie Saunders
+19  A: 

Use spl_object_hash() for that.

It returns an unique identifier for each object instance, and not the name of the class, so it seems more suitable for you.

azkotoki
If the objects are equal i.e. differing only by identity the object hashes produces by `spl_object_hash()` can appear very similar. I just tried it and I got this: a: 00000000462ff471000000005e39f75b b: 00000000462ff46c000000005e39f75bThose are different but you have to look carefully.
Ollie Saunders
Also, note the comment of planetbeing on the reference page about the hashes possibly being the same when the reference is destroyed.
koen
@Ollie Saunders, To correct this, you can take the hash (e.g. SHA1) of the `sql_object_hash()`. However, there *could* be collisions, but I don't think that's something to worry about in this case.
strager
A: 

spl_object_hash is only for PHP 5 >= 5.2.0. Whar about PHP 5.1.x?

WegDamit
You should better ask a new question specifically to PHP 5.1.x, not just post i as an answer. The "Ask Question" button is in the top right. More people will look at it if you start a new question.
sth
Liked to put it as a commentm but wasn't allowed: Staus to low...
WegDamit
A: 

Also note this manual page:

http://php.net/manual/en/function.uniqid.php

The comments are worth reading, eg

http://www.php.net/manual/en/function.uniqid.php#94959

koen
Not at all useful in the context of the question
meagar