getters and setters in php -


i have been coding in php , using codeigniter well, never got concept of getter , setter. mean ?

class foo {     protected $_bar;     public function setbar($value) {         $this->_bar = $value;     }     public function getbar()     {         return $this->_bar;     } } 

the getter , setter here methods allow access protected property $_bar. idea not directly allow access property, control access through api client code consume. way can change underlying state, while leaving public facing methods is. thus, less break client if changes occur.

another reason have them, when need add logic before or set property. instance, setter might validate , uppercase value

public function setbar($value) {     if(!is_string($value)) {         throw new invalidargumentexception('expected string');     }     $this->_bar = strtoupper($value); } 

or getter may lazy instantiate object

public function getbar() {     if($this->_bar === null) {         $this->_bar = new bar;     }     return $this->_bar; } 

some people criticize getter , setters boilerplate code, if not directly setting/getting property provide access to. discussion beyond scope though. read more @


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -