Skip to content

Instantly share code, notes, and snippets.

@matthewstokeley
Last active February 7, 2020 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewstokeley/10422786 to your computer and use it in GitHub Desktop.
Save matthewstokeley/10422786 to your computer and use it in GitHub Desktop.
php loop array and assign function name with value
<?php
// iterates through an array and calls the appropriate function
foreach ($key_array as $key_name) {
if(array_key_exists($key_name, $settings)) {
$function = 'set' . ucwords($key_name);
$this->$function($settings[$key_name]);
}
}
// v2 should use an iterator, and use a lookup table to declare the function. WIP
// iterates through an array and calls the appropriate function
class LocalIterator implements Iterator
{
private $position = 0;
private $array = array(
"a", "b", "c"
);
public __constructor()
{
$this->position = 0;
}
public function rewind() {
var_dump(__METHOD__);
$this->postion = 0;
}
public function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function previous() {
--$this->position;
}
public function valid() {
return isset($this->array[$this->position]);
}
public function end() {
$this->position = count($this->array);
}
}
$iterator = new LocalIterator();
foreach ($iterator as $key => $value) {
if(!array_key_exists($key, $settings)) {
continue;
}
$function = 'set' . ucwords($key_name);
$this->$function($settings[$key_name]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment