Skip to content

Instantly share code, notes, and snippets.

@kendru
Created June 26, 2012 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kendru/2996098 to your computer and use it in GitHub Desktop.
Save kendru/2996098 to your computer and use it in GitHub Desktop.
Get and set generic properties that are not known until runtime
<?php
class AccessibleClass {
protected $data;
public function __construct() {
$this->data = array();
}
public function __call( $method, $args ) {
if( 0 === ( $start = strpos($method, 'get') ) ) { // If the method is a getter
$var = strtolower(substr($method, 3, (strlen($method) - 3)));
if( isset($this->data[$var]) ) {
return $this->data[$var];
} else {
throw new Exception(
"Property, '$var', does not exist for class " . __CLASS__ );
}
} elseif( 0 === ( $start = strpos($method, 'set') ) ) { // If the method is a setter
$var = strtolower(substr($method, 3, (strlen($method) - 3)));
if( count($args) != 0 ) {
$this->data[$var] = $args[0];
} else {
throw new Exception(
"Could not set property, '$var', of class " . __CLASS__ . " without a value." );
}
} else {
throw new Exception( "No such method exists for class " . __CLASS__ );
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment