Last active
August 29, 2015 14:08
-
-
Save fijiwebdesign/5174a7bab4f655c55707 to your computer and use it in GitHub Desktop.
Retrieve human readable unique object Ids
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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