Php magic method __call() problem with get set

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.

$key = null should be replaced with $this->arrayData[$key] = null;

Have you looked at the ArrayAccess interface BTW? See Example #1 in the link to see how that works.

1 Like

Exactly! 10Q

Passing the array key as the first argument is a very strange design. If your instructor is insisting on it then okay. But if you have some choice then you really should rethink doing so.

1 Like

I would argue that anything using __call is a very strange design …

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.