Skip to content

Instantly share code, notes, and snippets.

@tonyseek
Created May 22, 2012 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyseek/2769113 to your computer and use it in GitHub Desktop.
Save tonyseek/2769113 to your computer and use it in GitHub Desktop.
Implementing dynamic getter and setter in PHP.
<?php
class ModelBase {
static $attr_accessible = array();
static $attr_readable = array();
static $attr_writable = array();
public function __get($attr) {
$getter = "get_{$attr}";
if (in_array($attr, static::$attr_accessible) || in_array($attr, static::$attr_readable)) {
return $this->$attr;
} else if (method_exists($this)) {
return $this->$getter();
} else {
trigger_error("attribute '{$attr}' is not found.");
}
}
public function __set($attr, $value) {
$setter = "set_{$attr}";
if (in_array($attr, static::$attr_accessible) || in_array($attr, static::$attr_writable)) {
$this->$attr = $value;
} else if (method_exists($this)) {
$this->$setter($value);
} else {
trigger_error("attribute '{$attr}' is not found.");
}
}
}
@HeinrichJulian
Copy link

Line 23: method_exists() expects 2 parameters

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