Posted By

Alexw on 12/19/09


Tagged

php oop getter setter


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

spf13
Blacksnipe


PHP Getters and Setters


 / Published in: PHP
 

OOP style getters and setters in PHP.

  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
Posted By: dbphp on February 9, 2010

I can't quite see the point of all that, performing string operations on function names isn't really going to be terribly performant when. Better to just make up individual get/sets for each variable re http://www.icurtain.co.uk/getset.php

You need to login to post a comment.