scanreg Posted January 25, 2012 Share Posted January 25, 2012 I know that magic __get and __set are invoked automatically when an object is instantiated, but what about stuff like getName() and setName() class NameClass { private $_name; public function getName() { return $this->_name; } public function setName($value) { $this->_name = $value; } } $someName = new NameClass(); $someName->setName('Bob'); echo $someName->getName(); 1. Could the setName() and getName() just as easily be named something generic like: hotName() coldName() class NameClass { private $_name; public function hotName() { return $this->_name; } public function coldName($value) { $this->_name = $value; } } $someName = new NameClass(); $someName->coldName('Bob'); echo $someName->hotName(); 2. Also, the setName() and getName() methods must be called manually, right? Unless they are manually called, they just sit there, do nothing, am I correct? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/255762-getters-and-setters-magic-versus-direct/ Share on other sites More sharing options...
scootstah Posted January 25, 2012 Share Posted January 25, 2012 1. Could the setName() and getName() just as easily be named something generic like: hotName() coldName() They can be named anything you want. They are simply methods in a class. 2. Also, the setName() and getName() methods must be called manually, right? Unless they are manually called, they just sit there, do nothing, am I correct? Yes and no. With the code you provided they won't do anything without being called manually. However, you could call them from magic methods (like __get and __set) if you wanted to. Quote Link to comment https://forums.phpfreaks.com/topic/255762-getters-and-setters-magic-versus-direct/#findComment-1311081 Share on other sites More sharing options...
scanreg Posted January 25, 2012 Author Share Posted January 25, 2012 Yes and no. With the code you provided they won't do anything without being called manually. However, you could call them from magic methods (like __get and __set) if you wanted to. Gotcha, if within the magic methods the regular methods could be called but otherwise they need to be called directly Thanks Quote Link to comment https://forums.phpfreaks.com/topic/255762-getters-and-setters-magic-versus-direct/#findComment-1311094 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.