Skip to content

Instantly share code, notes, and snippets.

@objectivehtml
Created August 22, 2012 17:29
Show Gist options
  • Select an option

  • Save objectivehtml/3427766 to your computer and use it in GitHub Desktop.

Select an option

Save objectivehtml/3427766 to your computer and use it in GitHub Desktop.
PHP Dynamic Setter/Getter Magic Method
<?php
public function __call($method, $args)
{
foreach(array('/^get_/' => 'get_' , '/^set_/' => 'set_') as $regex => $replace)
{
if(preg_match($regex, $method))
{
$property = str_replace($replace, '', $method);
$method = rtrim($replace, '_');
}
}
$args = array_merge(array($property), $args);
return call_user_func_array(array($this, $method), $args);
}
public function get($prop)
{
if(isset($this->$prop))
{
return $this->$prop;
}
return NULL;
}
public function set($prop, $value)
{
if(isset($this->$prop))
{
$this->$prop = $value;
}
}
@xeoncross

Copy link
Copy Markdown

Regex is expensive. Multiple regex matches each access would never fly in a production application. Use substr() or strpos() instead. You could also convert the regex to a single run if(preg_match('~^[gs]et_~', $method)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment