spl_object_hash for PHP < 5.2 (unique ID for object instances)

Posted by Rowan on Stack Overflow See other posts from Stack Overflow or by Rowan
Published on 2010-02-19T20:52:02Z Indexed on 2010/03/17 2:01 UTC
Read the original article Hit count: 298

I'm trying to get unique IDs for object instances in PHP 5+.

The function, spl_object_hash() is available from PHP 5.2 but I'm wondering if there's a workaround for older versions.

There are a couple of functions in the comments on php.net but they're not working for me. The first (simplified):

function spl_object_hash($object){
    if (is_object($object)){
        return md5((string)$object);
        }
    return null;
    }

does not work with native objects (such as DOMDocument), and the second:

function spl_object_hash($object){
    if (is_object($object)){
        ob_start();
        var_dump($object);
        $dump = ob_get_contents();
        ob_end_clean();
        if (preg_match('/^object\(([a-z0-9_]+)\)\#(\d)+/i', $dump, $match)) {
            return md5($match[1] . $match[2]);
            }
        }
    return null;
    }

looks like it could be a major performance buster!

Does anybody have anything up their sleeve?

© Stack Overflow or respective owner

Related posts about php

Related posts about spl-object-hash