View Single Post
Old 01-27-2008, 05:29 PM   #1 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Box Tripwire Class (Much like the Java "final" keyword for PHP)

Well, I created this little class - not for any particular purpose, because let's be honest, it's pretty useless, but it is quite nifty! Basically, all you have to do is arm (or set) a variable, and then let the class do the rest. If the variable value changes from what it was when you set it, an exception will be thrown.

We use it like so:

php Code:
class Tripwire
{
    private static $m_aVars;
    private static $m_bStarted;
    const MESSAGE = 'Variable "%s" has been modified from "%s" to "%s".';
   
    public static function init()
    {
        declare(ticks = 1);
        self::$m_bStarted = true;
        register_tick_function
        (
            create_function
            (
                null,
                'Tripwire::check();'
            )
        );
    }
   
    public static function set($szVar)
    {
        global ${$szVar};
       
        if(self::$m_bStarted == false)
        {
            self::init();
        }
       
        self::$m_aVars[] = array
        (
            'var' => $szVar,
            'data' => ${$szVar}
        );
    }
   
    public static function check()
    {
        if(!isset(self::$m_aVars))
        {
            return;
        }
       
        foreach(self::$m_aVars as $aVar)
        {
            global ${$aVar['var']};
           
            if(${$aVar['var']} != $aVar['data'])
            {
                throw new Exception(sprintf(self::MESSAGE, $aVar['var'], $aVar['data'], ${$aVar['var']}));
            }
        }
    }
}

try
{
    $szText = 'Adam';
    Tripwire::set('szText');
    $szText = 'Karl';
}
catch(Exception $pEx)
{
    die($pEx->getMessage());
}
Attached Files
File Type: php TalkPHP_Tripwire.php (1.0 KB, 251 views)
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
The Following 2 Users Say Thank You to Wildhoney For This Useful Post:
Alan @ CIT (01-27-2008), sketchMedia (06-02-2008)