Having associative array I need to create class with __call magic method that handles get, set, has, and unset.
My code:
class Data2 {
public $arrayData = ["firstname" => "Joe", "lastname" => "Doe", "hobby" => "play football"];
public function __call($method, $arguments = null) {
$prefix = substr($method, 0, 3);
//$arrayIndex = isset($arguments[0]) ? $arguments[0] : die("Nuttin");
if ($prefix == 'set' && count($arguments) == 2) {
$key = $arguments[0];
$value = $arguments[1];
//$key = substr($method, 3);
//$arrayIndex = isset($arguments[0]) ? $arguments[0] : null;
$this->arrayData[$key] = $value;
} else if ($prefix == 'get' && count($arguments) == 1) {
$key = $arguments[0];
if (array_key_exists($key, $this->arrayData)) {
return $this->arrayData[$key];
}
} else if ($prefix == 'has' && count($arguments) == 1) {
$key = $arguments[0];
return (array_key_exists($key, $this->arrayData)) ? 'true' : 'false';
} else if ($prefix == 'uns' && count($arguments) == 1) {
$key = $arguments[0];
if (!empty($key)) {
$key = null;
}
}
}
}
$data2 = new Data2();
echo$data2->setFirstName('firstname', 'Joe');
echo $data2->getFirstName('firstname');
echo $data2->hasFirstName('firstname');
echo $data2->unsFirstName('firstname'); // doesn't work
But, my $prefix == ‘uns’ doesn’t work for me, I am not sure what to do.