Created
June 26, 2012 14:27
-
-
Save kendru/2996098 to your computer and use it in GitHub Desktop.
Get and set generic properties that are not known until runtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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