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 is a workaround for older PHP 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?
I ran a couple of quick tests. I really think you’d be better off storing real callbacks in your bind() function using
bind('evt_name', array($obj, 'callback_function')). If you absolutely want to go the spl_object_hash route, rather than storing references with the event bindings, you’re looking at something like this:A var_dump / extract and hash id implementation:
A naive references implementation:
This one was basically 5-50x worse than the class-based reference function across the board, so it’s not worth worrying about.
A store references by class implementation:
And you end up with results that look like this. Summary: the class based references implementation performs best around n/50 classes–at its best, it manages to pull off 1/3 the performance of the
var_dumpbased implementation, and it’s usually much worse.The
var_dumpimplementation seems to be tolerable, though not ideal. But if you’re not doing too many of these lookups, it won’t be a bottleneck for you. Especially as a fallback for PHP < 5.2 boxen.