1

I have been coding in php and using codeigniter as well, never got the concept of getter and setter. What does it mean ?

ktm
  • 6,025
  • 24
  • 69
  • 95

1 Answers1

3
class Foo
{
    protected $_bar;
    public function setBar($value) {
        $this->_bar = $value;
    }
    public function getBar()
    {
        return $this->_bar;
    }
}

The getter and setter here are the methods that allow access to the protected property $_bar. The idea is not to directly allow access to the property, but to control access to it through an API for your client code to consume. This way you can change the underlying state, while leaving the public facing methods as is. Thus, you are less likely to break a client if changes occur.

Another reason to have them, is when you need to add logic before you get or set a property. For instance, a setter might validate and uppercase the value

public function setBar($value)
{
    if(!is_string($value)) {
        throw new InvalidArgumentException('Expected String');
    }
    $this->_bar = strtoupper($value);
}

or a getter may lazy instantiate some object

public function getBar()
{
    if($this->_bar === NULL) {
        $this->_bar = new Bar;
    }
    return $this->_bar;
}

Some people criticize getter and setters as boilerplate code, especially if they do not do anything than directly setting/getting the property they provide access to. That discussion is beyond scope though. Read more about it at

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 1
    +1 very consice and informative. May I simply suggest that the magic __get() and __set() can be useful if functionality such as pre or postprocessing a class variable needs to be added after the initial development, in order to avoid refactoring. – Fanis Hatzidakis Sep 23 '10 at 22:42