Software engineering notes

PHP class to manage read-only vars and arrays

Source code:


class Constants
{
    private $var_cache;

    public function set($key, $val)
    {
        if(isset($this->var_cache[$key]))
        {
            throw(new Exception("Constants->get() error: var $key has already been defined"));
        }
        else
        {
            $this->var_cache[$key] = $val;
        }
    }

    public function get($key)
    {
        return $this->var_cache[$key];
    }
}

Example usage:

$constants = new Constants();

$constants->set('base_url', 'www.domain.com/path');

...

$img_src_url = $constants->get('base_url').'/img/file.jpg';

echo "<img src='$img_src_url'/>";

Written by Erik

October 26, 2008 at 12:04 am

Posted in code

Tagged with

%d bloggers like this: