Aufgabe: Typsicheres Set
Geschrieben am 20. Dez 2008 von Cem Derin
Nils möchte ein bisschen Code schnorren und hat das ganze als “Aufgabe” getarnt. Er will, dass wir für ihn ein Typsicheres Set Implementieren. Ich hab mich, nach anfänglicher Bergriffsstutzigkeit auch mal daran versucht.
Hier mein Ergebnis:
/**
* Type safe set
*
* @author Cem Derin
*/
class TypeSafeSet extends ArrayObject {
/**
* Type of this set
*
* @var String
*/
protected $_type = null;
/**
* Constructor
*
* @param mixed $input
*/
public function __construct($input = null) {
if($input !== null) {
$this->_setType($input);
parent::__construct();
$this->append($input);
}
parent::__construct();
}
/**
* Appends a value if correct type
*
* @param mixed $input
*/
public function append($input) {
if(!$this->getType()) {
$this->_setType($input);
parent::append($input);
return;
} elseif($this->_checkType($input)) {
parent::append($input);
return;
}
throw new Exception('Set is for '. $this->getType().' values only. '. $this->getType($input). ' given.');
}
/**
* Returns the type of a given value
*
* @param mixed $input
* @return String
*/
public function getType($input = null) {
if(!$input) {
return $this->_type;
}
if(($type = gettype($input)) == 'object') {
return get_class($input);
} else {
return $type;
}
}
/**
* Sets the type by a given value
*
* @param mixed $input
* @access protected
*/
protected function _setType($input) {
$this->_type = $this->getType($input);
}
/**
* Checks whether a given value matches to the current set
*
* @param mixed $input
* @return Boolean
* @access protected
*/
protected function _checkType($input) {
if($this->getType($input) == $this->_type) {
return true;
}
return false;
}
}
#001
Hi, was bedeuten die Unterstriche vor den Methoden?