Erik's blog

Code, notes, recipes, general musings

PHP class to manage read-only vars and arrays

leave a comment »

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'/>";

Advertisements

Written by Erik

October 26, 2008 at 12:04 am

Posted in code

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: