views:

318

answers:

3

What are getters and setters in PHP5? Can someone give me a good example with an explanation?

+1  A: 

The PHP manual is really not very verbose on the issue, but there is a very detailed example that should explain a lot. Magic methods: Property overloading

Pekka
+2  A: 

Attributes of classes can be private. That means only the object can read and write its own private attributes. Therefore you need methods to do that. The methods that read and return an attribute value are called getters and those that write attributes are called setters. With these methods the classes can control what’s going out and what’s coming in. This concept is called encapsulation.

Gumbo
In some cases getters and setters are the opposite of encapsulation. If you have a getter AND a setter for a variable, then there's a good chance you need to change your design, because you're basically exposing that inner member. Why have setX, getX, setY, getY when you could use a more encapsulating 'moveTo', or 'moveBy' method?
Lotus Notes
+4  A: 

This is concept for data hiding (or encapsulation) in OOP. For example if you want to have a certain property in your class let's say 'Amount' and give the client of you class the option to change or extract its value You should make your variable 'Amount' private (not visible for those who use your class) and generate two methods a getter and a setter that manipulates your value (that are public).

The reason is to be able to validate data or manipulate it before setting or getting your value. Here is a brief example:

class test {

    private $count; //those who use your class are not able to see this property, only the methods above

    public function setCount( $value )    
    {
            //make some validation or manipulation on data here, if needed
        $this->count = $value;    
    }

    public function getCount()    
    {                
        return $this->count;    
    }    
}
anthares