Unique instance ID?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Ward
Forum Commoner
Posts: 74
Joined: Thu Jul 13, 2006 10:01 am

Unique instance ID?

Post 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?
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
Last edited by Jenk on Thu Jul 13, 2006 12:00 pm, edited 1 time in total.
Ward
Forum Commoner
Posts: 74
Joined: Thu Jul 13, 2006 10:01 am

Post 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.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.
Ward
Forum Commoner
Posts: 74
Joined: Thu Jul 13, 2006 10:01 am

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
Post Reply