1

Possible Duplicate:
String with array structure to Array

I have a static class which works as a registry, storing some relevant setting variables. Since it's static I cannot add/remove proprieties during runtime so, inside that class I have a generic object (can be an array) which stores those proprieties.

here's the code

class Settings
{
    private static $setsObj;
    public static function Set($key, $value)
    {
        self::$setsObj->$key = $value;
    }
    public static function Get($key)
    {
        if (strpos($key, '->') > 0)
        {
            $key = explode('->', $key);

            $n = count($key);

            $execute = 'return self::$setsObj->' . $key[0];

            for ($i = 1; $i < $n; $i++)
            {
                    $execute .= '["' . $key[$i] . '"]';
            }

            $execute .= ';';

            eval($execute);
        }
        else
        {
            return self::$setsObj->$key;
        }

    }
}

Now this enables me to get a determined property like this:

Settings::Get('property_name');

If that said property is an array, I can access an array subitem like this:

Setting::Get('property_name->subitem');

My question is:

Is using eval correct in this situation? It possible to make this work without using eval? Shall I change to a Singleton Pattern class and add properties directly to the parent object (some information is sensible, like DB Passwords)?

Community
  • 1
  • 1
Tivie
  • 18,374
  • 5
  • 54
  • 77

2 Answers2

0

untested

$cursor = self::$setsObj;
foreach (explode('->', $key) as $prop) {
    if (!is_object($cursor)) {
        //exception?
    }
    if (!isset($cursor->$prop)) {
        return null;
    }
    $cursor = $cursor->$prop;
}
return $cursor;
goat
  • 29,650
  • 7
  • 65
  • 92
0

I know my answer might sound silly but wouldn't this achieve what you are trying to do ? :

Settings::Set('foo', (object) array('bar' => 10));

var_dump(Settings::get('foo')->bar);
Pierre Fraisse
  • 949
  • 1
  • 11
  • 19