Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Something
- {
- protected $_another;
- public function __construct (array $options = null)
- {
- if (is_array($options)) {
- $this->setOptions($options);
- }
- }
- public function __set ($name, $value)
- {
- $method = 'set'.$name;
- if (!method_exists($this, $method)) {
- throw new Exception('Tried to set invalid property: '.$name);
- }
- $this->$method($value);
- }
- public function __get ($name)
- {
- $method = 'get'.$name;
- if (!method_exists($this, $method)) {
- throw new Exception('Tried to get invalid property: '.$name);
- }
- return $this->$method();
- }
- public function setOptions (array $options)
- {
- $methods = get_class_methods($this);
- foreach ($options as $key => $value) {
- $method = 'set'.ucfirst($key);
- if (in_array($method, $methods)) {
- $this->$method($value);
- }
- }
- return $this;
- }
- public function setAnother ($val)
- {
- $this->_something = $val;
- return $this;
- }
- public function getAnother ()
- {
- return $this->_another;
- }
- }
- ?>
- <?php
- // test case
- $something = new Something();
- $something->another = 'test';
- echo $something->another;
- ?>
- #Error:
- Fatal error: Uncaught exception 'Exception' with message 'Tried to set invalid property: _something' in /home/sss/Projects/my/public/test.php:19
- Stack trace:
- #0 /home/sss/Projects/my/public/test.php(47): Something->__set('_something', 'test')
- #1 /home/sss/Projects/my/public/test.php(21): Something->setAnother('test')
- #2 /home/sss/Projects/my/public/test.php(58): Something->__set('another', 'test')
- #3 {main}
- thrown in /home/sss/Projects/my/public/test.php on line 19
Add Comment
Please, Sign In to add comment