<?php
/**
 * Generates setters and getters out of given value and prints the code to screen, which can
 * simply be copy pasted into place
 *
 * Usage example with underscore type and array and string as elements:
 * <code>
 * $arr = array
 * (
 *	 'name',
 *   array('id', '_id')
 * );
 *
 * setnget_gen($arr, 1);
 *
 * // output:
 * //
 * // function set_name($name) { $this->name = $name; }
 * // function get_name() { return $this->name; }
 * // function set_id($id) { $this->_id = $id; }
 * // function get_id() { return $this->_id; }
 * </code>
 * 
 *---------------------------------------
 * Originally written by Kjetil Hårtveit.
 *		www.kjetil-hartveit.com
 *---------------------------------------
 *
 * @param array $arr Elements can be string or array:
 * if string, then the value will be used everywhere, including class variable name
 * if array then the first element will be method names, and (if exists) the second element
 * will be class variable name
 * @param int $type Types: 1=underscore (set_name()), 2=camelcase (setName())
 */
function setnget_gen($arr, $type=1)
{
	$str_arr = array(); # contains all the string pairs, all with an distinctive key
		foreach ($arr as $v)
		{
				if (is_array($v))
				{
					@list($name, $var_name) = $v;
					$var_name = $var_name ? $var_name : $name;
				}
				else
				{
					$name = $var_name = (string) $v;
				}

				switch ($type)
				{
					case 1: # underscore
					default: # note that type defaults to 1 if invalid type is given
						$str_arr[] = "function set_$name(\$$name) { \$this->$var_name = \$$name; }\r\n".
										"function get_$name() { return \$this->$var_name; }\r\n";
					break;
					case 2: # camelcase
						$str_arr[] = 'function set'.ucfirst($name)."(\$$name) { \$this->$var_name = \$$name; }\r\n".
										'function get'.ucfirst($name)."() { return \$this->$var_name; }\r\n";
					break;
				}
		}

	$str = implode('', $str_arr);
	echo nl2br($str);
}
?>