Php spl_object_hash uniqueness

I was just reading this and thinking about a possible solution to achieve unique IDs for objects in PHP.

Since spl_object_hash() returns an md5 hash of the internal pointer of an object an php reuses pointers you might wonder how to have unique IDs through your application. Well we still have microtime() and time goes forward never backward Wink

So just wrap `spl_object_hash()` adding `microtime()` to the hash, just once per object.

function wrap_spl_object_hash (&$obj) {
        if (!isset($obj->__microtime)) {
                $obj->__microtime = microtime(true);
                usleep(1);
        }
        return spl_object_hash($obj) . $obj->__microtime;
}

Taking the example from the cited post it would then be:

function wrap_spl_object_hash (&$obj) {
        if (!isset($obj->__microtime)) {
                $obj->__microtime = microtime(true);
                usleep(1);
        }
        return spl_object_hash($obj) . $obj->__microtime;
}

$transaction_ids = array();
for( $i=0; $i<10; $i++ ) {
        $transaction = (object)('transaction ' . $i);
        $transaction->microtime = microtime(true);
        $hash = wrap_spl_object_hash( $transaction );
        $transaction_ids[] = $hash;
}
print_r( $transaction_ids );

that prints:

Array
(
    [0] => 000000000fcf45b100000000429a20801251033333.0137
    [1] => 000000000fcf45b200000000429a20801251033333.014
    [2] => 000000000fcf45b100000000429a20801251033333.0141
    [3] => 000000000fcf45b200000000429a20801251033333.0142
    [4] => 000000000fcf45b100000000429a20801251033333.0143
    [5] => 000000000fcf45b200000000429a20801251033333.0146
    [6] => 000000000fcf45b100000000429a20801251033333.0147
    [7] => 000000000fcf45b200000000429a20801251033333.0148
    [8] => 000000000fcf45b100000000429a20801251033333.0149
    [9] => 000000000fcf45b200000000429a20801251033333.0151
)

There are two things though that I don't like:

  1. We are wrapping an internal function, that means having `wrap_spl_object_hash()` always available through all our code;
  2. We are slowing down execution with `usleep()` in order to have a unique value (try to remove usleep() and you will see that some ID won't be unique).

Let's hope this is a bug that will be soon solved.

© 2011 Devis Lucato @itbus.