Page 1 of 1

Unique instance ID?

Posted: Thu Jul 13, 2006 10:24 am
by Ward
I'm trying to find a good way to generate a unique instance ID for each object I create, so I can save its viewstate in a session. I know I can get the class name using 'get_class($this)', but that won't work for multiple instances of the same object. If I could return the actual variable name as a string, that might work, but there has to be a better way. Any ideas?

Posted: Thu Jul 13, 2006 10:45 am
by Jenk
I remember feyd posted a method from his Registry class of his making in snippets before it was nuked, it was along the lines of:

Code: Select all

<?php

class Registry
{
    private static $store = array();

    public static function addValue ($val)
    {
        do {
            $key = uniqid();
        } while (isset(self::store[$key]));

        self::store[$key] = $val;
        return $key;
    }

    public static function getValue ($key)
    {
        return (isset(self::store[$key]) ? self::store[$key] : FALSE);
    }
}

?>
The getValue method may not be suitable (due to return value) it's only there for the sake of it.

Posted: Thu Jul 13, 2006 11:58 am
by Ward
Thats a step in the right direction, but I wouldn't know the $key to use with getData. My idea is to have an object store it's state (dump all properties) to a session var. When the object reloads (say on page refresh), it will automatically re-init itself. I may be better off simply storing the serialized object in a session.

Posted: Thu Jul 13, 2006 12:01 pm
by Jenk
You can use the session to store the object, like you would any normal variable..

Code: Select all

$_SESSION['obj'] = new Object;
That may get a frown from some, though.

Posted: Thu Jul 13, 2006 12:18 pm
by Ward
Yeah, I've read that storing entire objects in sessions will waste server memory. It makes sense, I don't really need to store all of the object methods, only the properties.

Posted: Thu Jul 13, 2006 12:46 pm
by Ollie Saunders
Yeah, I've read that storing entire objects in sessions will waste server memory. It makes sense, I don't really need to store all of the object methods, only the properties.
Unlike JS PHP will only store the properties.