Skip to content

Instantly share code, notes, and snippets.

@timw4mail
Created April 16, 2014 19:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timw4mail/10925996 to your computer and use it in GitHub Desktop.
Save timw4mail/10925996 to your computer and use it in GitHub Desktop.
Trait for naive getter/setter methods
<?php
/**
* Trait to get rid of naive getter/setter boilerplate
*/
trait GetSet
{
/**
* Dynamically create getters/setters
*
* @param string $func
* @param array $args
* @return mixed
*/
public function __call($func, $args)
{
$type = substr($func, 0, 3);
$val = strtolower(substr($func, 3));
$valid_types = array(
'get' => 'get',
'set' => 'set'
);
if ( ! property_exists($this, $val) || ! isset($valid_types[$type])) {
return NULL;
}
// Auto-magical getters and setters
if ($type === 'get') {
return $this->$val;
} elseif ($type === 'set') {
$this->$val = current($args);
}
}
}
// End of GetSet.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment