note 116044 added to function.spl-object-hash

From: Date: Sat, 01 Nov 2014 21:09:54 +0000
Subject: note 116044 added to function.spl-object-hash
Groups: php.notes 
Request: Send a blank email to php-notes+get-200767@lists.php.net to get a copy of this message
To get human readable unique object Ids with the Object classname prepended I have this function. The return from spl_object_hash() isn't very readable. Even a hash of it is still a bit hard to read. For those that need something in between, you could use crc32(spl_object_hash($object)). <?php /** * Create a unique String for each object with classname and object number concatenated. eg: MyClass_1 or MyClassNamespace\MyClass_2 * @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 ?> ---- Server IP: 72.52.91.14 Probable Submitter: 176.205.19.185 ---- Manual Page -- http://php.net/manual/en/function.spl-object-hash.php Edit -- https://master.php.net/note/edit/116044 Del: integrated -- https://master.php.net/note/delete/116044/integrated Del: useless -- https://master.php.net/note/delete/116044/useless Del: bad code -- https://master.php.net/note/delete/116044/bad+code Del: spam -- https://master.php.net/note/delete/116044/spam Del: non-english -- https://master.php.net/note/delete/116044/non-english Del: in docs -- https://master.php.net/note/delete/116044/in+docs Del: other reasons-- https://master.php.net/note/delete/116044 Reject -- https://master.php.net/note/reject/116044 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#200767) next »