我有使用words.separated.by.dots鍵保存數據存儲/數據訪問類,它成爲如下:PHP的算法 - 如何實現,如果沒有EVAL
$object = new MyArray()
$object->setParam('user.name','marcelo');
$object->setParam('user.email','[email protected]');
$object->getParams();
/*
array(
'user' => array(
'name' => 'marcelo',
'email' => '[email protected]'
)
);
*/
據工作,但unsetParam()方法實施起來非常可怕。發生這種情況是因爲我不知道如何在沒有eval()函數的情況下實現這個功能。雖然它在工作,但我發現它是一個非常具有挑戰性的算法,並且您可能會發現試圖在沒有eval()的情況下實現這一點。
class MyArray {
/**
* @param string $key
* @return Mura_Session_Abstract
*/
public function unsetParam($key)
{
$params = $this->getParams();
$tmp = $params;
$keys = explode('.', $key);
foreach ($keys as $key) {
if (!isset($tmp[$key])) {
return $this;
}
$tmp = $tmp[$key];
}
// bad code!
$eval = "unset(\$params['" . implode("']['", $keys) . "']);";
eval($eval);
$this->setParams($params);
return $this;
}
}
測試方法:
public function testCanUnsetNestedParam()
{
$params = array(
'1' => array(
'1' => array(
'1' => array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
),
'2' => array(
'1' => 'one',
'2' => 'two',
'3' => 'three',
),
)
),
'2' => 'something'
);
$session = $this->newSession();
$session->setParams($params);
unset($params['1']['1']['1']);
$session->unsetParam('1.1.1');
$this->assertEquals($params, $session->getParams());
$this->assertEquals($params['1']['1']['2'], $session->getParam('1.1.2'));
}
創意使用參考:) – Kato
非常好!非常感謝你! – Marcelo