Better use of a Getter method in PHP

You are probably familiar with getters and setters in object-oriented code. Usually they are something like this:

public function GetId(){
   return $this->id;
}
public function SetId($value=0){
   $this->id = $value;
}

Normally I improve these two methods by setting them into one method, like this:

public function Id($value=null){
   if($value == null){
      return $this->id;
   } else {
      $this->id = $value;
   }
}

But when doing this you have no place to add arguments into the getter method, based on the idea of a improved getter. Having an input argument as the fallback value if what you are getting is the false value. This is the new getter:

public function GetId($fallback=0){
   if(!$this->id || $this->id == 0)){
      return $fallback;
   } else {
      return $this->id;
   }
}

For an id this kind of fallback functionality may not make that much sense(but it might), but for a GetName or other it probably is. Consider this:

$html = 
'<input name="name" value="'.
($obj->GetName()?$obj->GetName():'Please enter your name')
.'" />';

Now you can replace it with this reducing unneccessary logic from the presentation:

$html = 
'<input name="name" value="'.
$obj->GetName('Please enter your name')
.'" />';
About these ads

2 Responses to Better use of a Getter method in PHP

  1. Faysal Ahmed says:

    Reblogged this on Faysal Ahmed.

  2. gcbenison says:

    A common idiom in Scheme (it’s where I come from :)) is to use ‘or’ for defaulting; the example in this post would look something like this -

    `(input
    (@ (name “name”)
    (value ,(or (getname) “please enter your name”))))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: