Dynamic Getter/Setters for PHP

November 23rd, 2007

We use the magic __call method in PHP which is called on an object when a declared function is called on it but it does not exist. This behaviour allows us to have default getters/setters but if we want specific behaviour for a get/set we just have to add the function to the class and __call will no longer be used for that class attribute.

  1. class GetSetExample{
  2.  
  3. /**
  4. * Dynamic getters and setters than maintain getX and setX formati. They can be overwritten
  5. * if custom processing is needed
  6. *
  7. * @param string $method
  8. * @param array $arguments
  9. * @return mixed
  10. */
  11. function __call($method, $arguments) {
  12.  
  13. #Is this a get or a set
  14. $prefix = strtolower(substr($method, 0, 3));
  15.  
  16. #What is the get/set class attribute
  17. $property = substr($method, 3);
  18.  
  19. if (empty($prefix) || empty($property)) { #Did not match a get/set call
  20. throw New Exception("Calling a non get/set method that does not exist: $method");
  21. }
  22.  
  23. #Check if the get/set paramter exists within this class as an attribute
  24. $match=false;
  25. foreach($this as $class_var=>$class_var_value){
  26. if(strtolower($class_var) == strtolower($property)){
  27. $property=$class_var;
  28. $match=true;
  29. }
  30. }
  31.  
  32. #Get attribute
  33. if ($match && $prefix == "get" && (isset($this->$property) || is_null($this->$property)) {
  34. return $this->$property;
  35. }
  36.  
  37. #Set
  38. if ($match && $prefix == "set") {
  39. $this->$property = $arguments[0];
  40. }
  41. elseif (!$match && $prefix == "set"){
  42. throw new Exception("Setting a variable that does not exist: var:$property value: $arguments[0]");
  43. }
  44. else{
  45. throw new Exception("Calling a get/set method that does not exist: $property");
  46. }
  47. }
  48.  
  49. }
blog comments powered by Disqus