Oct '12

Often I have need to get and set object data and rather than writing individual functions for each call, I use PHP’s built-in __call function.
This example assumes that you have an object-scope array called ‘data’, but can be easily adapted to any other data structure.

public function __call($method, $args) {
	$opt = substr($method, 0, 3);
	$field = strtolower(substr($method, 3));

	if($opt == 'get')
		return $this->data[$field];
	elseif($opt == 'set' && $args)
		$this->data[$field] = $args[0];
	else {
		//any other logic here