I have a bunch of strings like “memory.caching” and “server.base.url”. Within my configuration object each part of the key “.” is equal to a key within an array, the value could be another array and the last would be the value so “memory.caching” would equate to.
$config = array(
"memory" => array(
"caching" => true
)
);
I want to create a setter method. I have ended up with the below code, but that won’t work for three or four levels of depth. How can I do it without adding multiple else/if clauses.
public function set($k, $v) {
$parts = explode(".", $k);
// Start sucky code.
if (count($parts) == 2)
{
$this->config[$parts[0]][$parts[1]] = $val;
}
}
I was thinking some form of loop with assigning by reference like below, but I couldn’t get it to work.
public function set($k, $v) {
$parts = explode(".", $k);
$tmp = $this->config;
foreach ($parts as $p) {
$tmp &= $tmp[$p];
}
$tmp = $v;
}
Any ideas on how I could achieve this?
To set a value…
CodePad.
To get a value…
CodePad.