Object ID

I was writing this post about objects in PHP needing unique ID, but now 5.2 is out and it has spl_object_hash() function which does it. Too bad it’s not documented in the manual, but besides that it seems to be just what I wanted.  But I’d hate to waste all the effort of writing it, so I’ll make it about why I think it’s a good idea.

Objects in PHP 5 are perceived by the engine as a (handle, handler table) pair. Which effectively means that each object has an unique ID (note that this ID has mostly nothing to do with pointers, etc. – for example, more than one zval may have some handle/handler pair, meaning they refer to the same object). You can sort of see this ID if you do var_dump() on an object – you’d see something like:

object(stdClass)#1 (0) {

#1 there is the handle of the object. Handler table is the same for all objects created from user-defined classes, though some objects – like Java or COM objects – would have different one.

However, before 5.2 there was no way (except for the perverted way of capturing var_dump() output and parsing it, I guess 🙂 to access this object ID – and even more interesting the full object ID – from a PHP script. This access might be very useful for things like serialization of complex object structures, RPC and such – when it’s important to know if two variables point to the same object and/or fetch objects by some unique ID.

One could, of course, create “base object” class which provides custom ID. But since the engine already has one, it’s better to use it.

Only thing I have doubts about is using of MD5 in this  function. MD5 is somewhat expensive function, if there’s some system which uses it a lot it might be too expensive.  Fortunately, since these IDs are transient, we could easily replace it if it proves a problem.


3 thoughts on “Object ID

  1. It is exactly the same thing.

    $sc1 = new stdClass();
    $sc2 = new stdClass();
    echo spl_object_hash($sc1)."---".spl_object_hash($sc2);


    Strange, eh?
    To quote the PHP manual:var_dump(spl_object_hash(new stdClass()), spl_object_hash(new stdClass()));

    Running this alone will usually generate the same hashes, since PHP reuses the internal handle for the first stdClass after it has been dereferenced and destroyed when it creates the second stdClass.

  2. It’s not quite the same thing. spl_object_hash() just hashes the properties, so identical instances will have the same hash.

    echo spl_object_hash(new stdClass) . '---' . spl_object_hash(new stdClass);


Comments are closed.