Skip to content

Instantly share code, notes, and snippets.

@fijiwebdesign
Last active August 29, 2015 14:08
Show Gist options
  • Save fijiwebdesign/5174a7bab4f655c55707 to your computer and use it in GitHub Desktop.
Save fijiwebdesign/5174a7bab4f655c55707 to your computer and use it in GitHub Desktop.
Retrieve human readable unique object Ids
<?php
/**
* @param Object $obj The Object to create an Id for
* @return String A human readable unique ID for the Object
*
* @internal Requires PHP5.2.0
* @see http://php.net/manual/en/function.spl-object-hash.php
*/
function get_obj_id($obj)
{
static $hashes = array();
$class = get_class($obj);
$hashes[$class] = isset($hashes[$class]) ? $hashes[$class] : array(null);
$hash = spl_object_hash($obj);
if (!($key = array_search($hash, $hashes[$class]))) {
$hashes[$class][] = $hash;
$key = array_search($hash, $hashes[$class]);
}
return $class . '_' . $key;
}
// Example
// ----------------------
$obj = new StdClass;
$id = get_obj_id($obj);
echo $id; // stdClass_1
$obj = new StdClass;
$id = get_obj_id($obj);
echo $id; // stdClass_2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment