Location: PHPKode > scripts > Constant Array > ArrConst.class.php
/*
 * CLASS TO GENRATE CONSTANT ARRAY
 * @author Sourav Ray
 * @author cleaned up and debugged by Ville Walveranta 2011-01-29
 * @version 2.0.1
 * @name ArrConst.class.php
 * @Note: 	ArrConst Version 2.0.0 consist a major change in Get method
 *			Now with the new get method it is possible to get 
 *			back the value of a particular element of the Array Constant
 * @Note:   ArrConst Version 2.0.1 has been reformatted and a bug in 
 *          selected index return has been fixed; now both numeric and
 *          associative array index keys work.		
 * ---------------------------------------------------------------------------
 */ 

class ArrConst {
		
	// Setter method: sets the array as a constant
	public static function set($constName, $paramArray) {
		if ($paramArray) {
			if (is_array($paramArray)) {
				if ($constName) {
					if (defined($constName)) {
						throw new Exception('ArrConst Error: Constant name in use');
					} else {
						try {
							define($constName, var_export($paramArray, true));
						} catch (Exception $e) {
							throw new Exception('ArrConst Error: Unknown error');
						}
					}
				} else {
					throw new Exception('ArrConst Error: No Const name');
				}
			} else {
				throw new Exception("ArrConst Error: Non array Constan can't be define");
			}
		} else {
			throw new Exception('ArrConst Error: Void array');
		}
	}
		
	// Getter method: returns the array from the constant
	public static function get($constName, $element = NULL) {
		if ($constName) {
			try {	
				if (is_null($element)) {
					return eval('return '.$constName.";");
				} else {
					// get serialized constant
					$constArray = eval('return '.$constName.";");
					// explode element request (in case more than one element are requested, comma separated)
					$keyArr = explode(',',$element);
					// init return array
					$returnArray = array();
					// get number of positions in element request array and convert to an array index
					$keyArrMaxIdx = count($keyArr) - 1;
					// get max index of the constant array
					$constArrayMaxIdx = count($constArray) - 1;
			
					try {
						for ($i=0; $i <= $keyArrMaxIdx; $i++) {
							// make sure the element request key is valid before push
							if ($keyArr[$i] != NULL && $keyArr[$i] != ' ' && array_key_exists($keyArr[$i], $constArray)) {
								array_push($returnArray, $constArray[$keyArr[$i]]);
							} else {
								throw new Exception('ArrConst Error: Bad Request Array Element');
							}
						}
					} catch (Exception $e) {
						print $e->getMessage();
					}
					return $returnArray;
				}
			} catch (Exception $e) {
				throw new Exception('ArrConst Error: Unknown error');
			}				
		} else {
			throw new Exception('ArrConst Error: Invalid Constant Name');
		}
	}
}
Return current item: Constant Array