Skip to content

Instantly share code, notes, and snippets.

@kibao
Created August 24, 2012 12:12
Show Gist options
  • Save kibao/3449907 to your computer and use it in GitHub Desktop.
Save kibao/3449907 to your computer and use it in GitHub Desktop.
[PHP] Magic getters, setters for Object.
/**
* Magic getters and setters.
* Example:
* Properties:
* - name
* - created_at
*
* Magic methods:
* - setName($name)
* - getName()
* - hasName()
*
* - setCreatedAt($created_at)
* - getCreatedAt()
* - hasCreatedAt()
**/
class MyObject {
public function __call($name, array $arguments) {
$key = preg_replace_callback(
'|[A-Z]|',
create_function(
'$matches',
'return "_" . strtolower($matches[0]);'
),
strtolower(substr($name, 3, 1)) . substr($name, 4)
);
$value = isset($arguments[0]) ? $arguments[0] : null;
switch (substr($name, 0, 3)) {
case 'get':
if (property_exists($this, $key)) {
return $this->$key;
}
break;
case 'set':
if (property_exists($this, $key)) {
$this->$key = $value;
return $this;
}
break;
case 'has':
if (property_exists($this, $key)) {
return $this->$key !== null;
}
break;
}
throw new \Exception('Method "' . $name . '" does not exist and was not trapped in __call()');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment