Created
August 22, 2012 17:29
-
-
Save objectivehtml/3427766 to your computer and use it in GitHub Desktop.
PHP Dynamic Setter/Getter Magic Method
This file contains hidden or 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 | |
| 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; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Regex is expensive. Multiple regex matches each access would never fly in a production application. Use
substr()orstrpos()instead. You could also convert the regex to a single runif(preg_match('~^[gs]et_~', $method)).