Question

What are getters and setters in PHP5?

Can someone give me a good example with an explanation?

Was it helpful?

Solution

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;    
    }    
}

OTHER TIPS

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.

Getters and Setters are quite new concept in PHP 5 in the form of two magical functions __get() and set(). These two functions set or get property value of an object dramatically as explained in the following example.

class Datatype{
private $thing;
public function _set($k,$v){
 $this->$k = $v;
}
public function __get($k){
 return $this->$k;
}
}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top