PHP Getters and Setters


/ Published in: PHP
Save to your folder(s)

OOP style getters and setters in PHP.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. class Person
  4. {
  5. private $first;
  6. private $last;
  7.  
  8. public setName ($name)
  9. {
  10.  
  11. }
  12.  
  13. public getName ($name)
  14. {
  15.  
  16. }
  17.  
  18. public function __set ($name, $value)
  19. {
  20. $key = strtoupper(substr($name, 1)) . strtolower(substr($name, 0, 1));
  21. $setter = 'set' . $key;
  22.  
  23. if (method_exists($this, $setter)) {
  24. $this->$setter($value);
  25. return $value;
  26. }
  27.  
  28. trigger_error('Undefined property via ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
  29. }
  30.  
  31. public function __get ($name)
  32. {
  33. $key = strtoupper(substr($name, 1)) . strtolower(substr($name, 0, 1));
  34. $getter = 'set' . $key;
  35.  
  36. if (method_exists($this, $getter)) {
  37. return $this->$getter();
  38. }
  39.  
  40. trigger_error('Undefined property via ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
  41. }
  42. }
  43.  
  44. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.