Question : OOP, classes, accessor/mutator question (newbie)

Hi, I've been fiddling with PHP for years, but only just started to grasp OOP style development.

So... I'm writing my first series of classes and using loads of accessor and mutator functions (because apparently 'it is the done thing'). A question that quickly springs to mind is, do I HAVE to use two functions for the accessor and mutator or can I combine the two? e.g.

function SetGetThing($stin=FALSE) {
    if (!$stin) {
        return $this->thing;
    }
    else {
        $this->thing = $stin;
    }
}

Seems to me that would almost halve the number of functions (not to mention phpdoc text) in my classes. But... does it break some higher law of OOP and anger the gods? :)

Cheers!

Answer : OOP, classes, accessor/mutator question (newbie)

It might be worth pointing out here, the reason for get/set functions. I find that there are often a lot of misunderstandings in this area and people complain about all that "unnecessary typing".

In many classes there are related data items where the value of one property may depend of the value of another. A simple example would be a date - the number of days is 31 except for Feb, Apr, Jun, Sept and Nov. Therefore the last thing you want is somebody OUTSIDE the class doing

$myClass->days = 31;

for any of the "short" months. It's OK for the long months. By using the setDays accessor you can prevent this

function setDays( $d ) {
     if ( $d > 30  && $this->month = .... feb, apr..etc )
          die("Error at line " . __LINE__ . " in script " . __FILE__ . " - date out of range");

     $this->days = $d;
}


So you have prevented an error getting into the system. Even where values are non-dependent you can and should enforce validation checks. For instance if a value can only have a range of zero to 59 then enforce that and either throw an error, display a message of substitute a default - whatever is appropriate for your data.

View the "set" methods as a validation filter for all your data and make sure that all properties are declared either protected or private (protected is the "norm" for 90% of all code)
Random Solutions  
 
programming4us programming4us