Guest User

Untitled

a guest
Jul 18th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. <?php
  2.  
  3. class Something
  4. {
  5. protected $_another;
  6.  
  7. public function __construct (array $options = null)
  8. {
  9. if (is_array($options)) {
  10. $this->setOptions($options);
  11. }
  12. }
  13.  
  14. public function __set ($name, $value)
  15. {
  16. $method = 'set'.$name;
  17. if (!method_exists($this, $method)) {
  18. throw new Exception('Tried to set invalid property: '.$name);
  19. }
  20. $this->$method($value);
  21. }
  22.  
  23. public function __get ($name)
  24. {
  25. $method = 'get'.$name;
  26. if (!method_exists($this, $method)) {
  27. throw new Exception('Tried to get invalid property: '.$name);
  28. }
  29. return $this->$method();
  30. }
  31.  
  32. public function setOptions (array $options)
  33. {
  34. $methods = get_class_methods($this);
  35. foreach ($options as $key => $value) {
  36. $method = 'set'.ucfirst($key);
  37. if (in_array($method, $methods)) {
  38. $this->$method($value);
  39. }
  40. }
  41. return $this;
  42. }
  43.  
  44. public function setAnother ($val)
  45. {
  46. $this->_something = $val;
  47. return $this;
  48. }
  49.  
  50. public function getAnother ()
  51. {
  52. return $this->_another;
  53. }
  54. }
  55. ?>
  56. <?php
  57. // test case
  58. $something = new Something();
  59. $something->another = 'test';
  60. echo $something->another;
  61. ?>
  62.  
  63. #Error:
  64. Fatal error: Uncaught exception 'Exception' with message 'Tried to set invalid property: _something' in /home/sss/Projects/my/public/test.php:19
  65. Stack trace:
  66. #0 /home/sss/Projects/my/public/test.php(47): Something->__set('_something', 'test')
  67. #1 /home/sss/Projects/my/public/test.php(21): Something->setAnother('test')
  68. #2 /home/sss/Projects/my/public/test.php(58): Something->__set('another', 'test')
  69. #3 {main}
  70. thrown in /home/sss/Projects/my/public/test.php on line 19
Add Comment
Please, Sign In to add comment