Skip to content

Instantly share code, notes, and snippets.

@SeanJA
Created April 1, 2010 05:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeanJA/351387 to your computer and use it in GitHub Desktop.
Save SeanJA/351387 to your computer and use it in GitHub Desktop.
<?php
/**
* @property-read string $class_name
*/
abstract class rootClass{
/**
* Contains the data for this class
* @var array
*/
protected $data = array();
/**
*
*/
public function __construct(){
$this->addProperty('class_name', '');
$this->setProperties();
}
/**
* Add a property to this class
* @param string $var the property being added
* @param mixed $default the default value
*/
protected function addProperty($var, $default = ''){
$this->data[$var] = $default;
}
/**
* Set the properties of this subclass
*/
abstract protected function setProperties();
/**
* Get the name of this class
* @return string
*/
public function __toString(){
return get_class($this);
}
/**
*
* @param mixed $var
* @return mixed
*/
public function __get($var){
if(array_key_exists($var, $this->data)){
$value = $this->data[$var];
} else {
throw new Exception($var . ' does not exist in ' . $this->class_name);
}
$function = '_get'.strtolower(str_replace('_', '', $var));
if(method_exists($this, $function)){
$value = $this->$function($value);
}
return $value;
}
/**
* Set a variable in the class
* @param string $var
* @param mixed $value
* @return mixed
*/
public function __set($var, $value){
$function = '_set'.strtolower(str_replace('_', '', $var));
if(method_exists($this, $function)){
$this->data[$var] = $value = $this->$function($value);
} elseif(array_key_exists($var, $this->data)) {
$this->data[$var] = $value;
}
return $value;
}
/**
* Get the class name
*/
protected function _getClassName(){
return $this->__toString();
}
/**
* Stop the setting of the classname
*/
protected function _setClassName(){
throw new Exception('What\'re you trying to pull?');
}
}
/**
* @property string $var_one
* @property number $var_two
*/
class childClass extends rootClass{
/**
* Set the default properties for this class
* @see rootClass::setProperties
*/
protected function setProperties(){
$this->addProperty('var_one', '');
$this->addProperty('var_two', '');
}
/**
* Make sure that var_one is not 'test' and is a string
* @param $value
* @return string
*/
protected function _setVarOne($value){
if(!is_string($value)){
throw new Exception('var_one needs to be a string');
}
if($value == 'test'){
throw new Exception('var_one cannot be "test".');
}
return $value;
}
/**
* Make sure that var_two is numeric, if it is not set it to 0
* @param number $value
* @return number
*/
protected function _setVarTwo($value){
if(!is_numeric($value)){
$value = 0;
}
return $value;
}
}
$c = new childClass();
$c->var_one = 'test';
echo $c->class_name;
echo $c->var_one;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment