LemonInflux Posted June 8, 2008 Share Posted June 8, 2008 Just a quick question, I was wondering what the difference is between $class->_var = true; (private var) and just using $class->var = true; (public var) without __set or __get? Quote Link to comment https://forums.phpfreaks.com/topic/109235-whats-the-point-of-__set-and-__get/ Share on other sites More sharing options...
redbullmarky Posted June 8, 2008 Share Posted June 8, 2008 using __set and __get magic methods can have all sorts of nice uses. personally i use it for 'models'. So: <?php class User { private $data = array(); // holds user record data public function __set($varname, $value) { $this->data[$varname] = $value; } public function __get($varname) { return isset($this->data[$varname]) ? $this->data[$varname] : null; } } $user = new User(); $user->email = 'test@test.com'; // sets User::$data['email'] ?> this way, i know that the $data property ONLY holds info about the user, not tonnes of other unrelated properties. You can also use these magic setters and getters to control what can or cannot be set from outside the class - ie, enforcing a certain way of using your class. Quote Link to comment https://forums.phpfreaks.com/topic/109235-whats-the-point-of-__set-and-__get/#findComment-560360 Share on other sites More sharing options...
keeB Posted June 8, 2008 Share Posted June 8, 2008 __set and __get methods are mainly used for open ended data structures, and generally breaks encapsulation (because every class property is now essentially public.) As you can see, the main draw back is the developer using your API can add properties to a class at their leisure. Quote Link to comment https://forums.phpfreaks.com/topic/109235-whats-the-point-of-__set-and-__get/#findComment-560516 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.