次のようなクラス内のデータを動的に取得しようとしています:
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 でデータを設定/取得したいのですが、ところで配列を呼び出します: function(fist.second.third.four.etc)。
編集:
爆発で関数を作成できます。その可能性を探りましたが、次のような関数を使用すると:
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]) または 1 次元 ($this->config[one]) の配列の値を取得する必要がある場合、関数は結果を処理できません。N次元の配列を取得したい。
私もこの解決策を試しました: $リターン = '';
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 内の配列を編集しません。これは文字通り config['site']['favicon'] と呼ばれる $this 内に新しい値を作成します。
どうすればできるのかわかりません。多くの方法を試しましたが、予想通りの結果が得られませんでした。手伝ってくれてありがとう。