How to find Object ID in PHP?

Viewed 37537

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?

4 Answers

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.

Edit:

For PHP < 5.2.x users, see this answer.

⚠️ PHP 7.2.0 introduces spl_object_id()!

$test = (object)[];
var_dump(spl_object_id($test)); # int(1)
Caveat emptor(?):

When an object is destroyed, its id may be reused for other objects.

Related