我试图在这样的类中动态地获取数据:
Class foo
{
private $config=array();
public __construct(){
$this->config['site']['title'] = 'XXXXX';
$this->config['site']['favicon'] = 'XXXXX.ico';
$this->config['site']['keywords'] = array('page','cute','other');
$this->config['otherthing'] = 'value';
/**etc**/
}
public function set($name,$value)
{
$tmp = explode('.',$name);
/** i dont know what i can do here **/
}
public function get($name)
{
$tmp = explode('.',$name);
/** i dont know what i can do here **/
}
}
$thing = new foo;
$this->set('site.keywords',array('other','keywords'));//this change a data inside foo->config['site']['keywords']
echo $this->get('site.title'); // gets data inside foo->config['site']['title']
echo $this->get('otherthing'); // gets data inside foo->config['otherthing']
数组维度可以动态更改,我想在 foo->config 中设置/检索数据,顺便调用数组:函数(fist.second.third.four.etc)。
编辑:
我可以使用explode 创建一个函数,我探索了这种可能性,但是如果我使用这样的函数:
function get($name)
{
$tmp = explode('.',$name);
if(isset($this->config[$tmp[0]][$tmp[1]]))
return $this->config[$tmp[0]][$tmp[1]];
return '';
}
当我需要在 3 维($this->config[one][two][tree])或一维($this->config[one])中获取数组值时,函数无法处理结果。我想获得 N 维数组。
我也尝试过这个解决方案: function nameToArray($name) { $tmp = explode('.',$name); $return = '';
foreach($tmp as $v)
{
$return .= "['{$v}']";
}
return 'config'.$return;
}
function set($name,$value)
{
$this->{$this->nameToArray} = $value;
}
$foo->set('site.favicon','something.ico');
但这不会在 $foo->config 中编辑数组,而是在 $this 中创建一个新值,字面意思是 config['site']['favicon']。
我不知道我该怎么做,我尝试了很多方法,但我无法得到预期的结果。感谢帮助。