I am trying to create a function (unless one already exists?) which is supposed to accept an “unlimited” amount of arguments (using func_get_args()
) to find the value of an array key. Regardless of how deep within the array it is to be found.
Say if I would use $registry->getSetting( 'template', 'default' );
I am supposed to get the value of $this->properties['settings']['template']['default']
or if I would you $registry->getSetting( 'users', 1, 'name', 'first' );
I would expect it to return the value of $this->properties['users'][1]['name']['first']
(just a second example with a couple of extra arguments).
Now, to do something like this, I could count the amount of arguments passed using func_num_args()
and then do a switch with different cases. Although, this would limit it to a certain amount of keys.
So I am asking you if there is a way of doing this, to allow an “unlimited” amount rather than a fixed amount of arguments to access a deeper key of an array.
<?PHP class Registry { // Values are actually fetched from a config file, but for easier understanding private $properties = array( 'settings' => array( 'template' => array( 'default' => 'default', 'caching' => TRUE ) ) ); public function getSetting( ) { // do something like // return $this->properties['settings'][func_get_args( )]; } } ?>
Any help whatsoever is highly appreciated.
Thank you!
Advertisement
Answer
<?PHP class Registry { // Values are actually fetched from a config file, but for easier understanding private $properties = array( 'settings' => array( 'template' => array( 'default' => 'default', 'caching' => TRUE ) ) ); public function getSetting() { $result = $this->properties; foreach (func_get_args() as $arg) { if (isset($result[$arg])) { $result = $result[$arg]; } else { return; } } return $result; } } $r = new Registry(); var_dump($r->getSetting('settings', 'template', 'default')); ?>