Page 1 of 1

Getter and Setter methods

Posted: Fri Jun 22, 2007 3:58 pm
by timclaason
Can someone explain to me what getter and setter methods are and how they are used?

I've searched the web and this forum, but I can't find a concise answer.

Posted: Fri Jun 22, 2007 4:57 pm
by djot
-
perhaps something like this, don't know ...

Code: Select all

<?php

class SetNGet {
  function Set($var) {
    $this->var = $var;
  }

  function Get() {
    return $this->var;
  }
}

$obj = new SetNGet();
$obj->Set('hello world');
print $obj->Get();

?>
djot
-

Posted: Fri Jun 22, 2007 5:24 pm
by RobertGonzalez
Are you talking about magic methods, or just the concept of getters and setters?

Posted: Fri Jun 22, 2007 5:32 pm
by pickle
"Setters" are traditionally functions that set variables in objects, while "Getters" are functions that retrieve those values.

Code: Select all

class Me
{
  private $height;

  function setHeight($feet)
 {
  $this->height = $feet;
 }

 function getHeight()
 {
   return $this->height;
 }
}
Usage:

Code: Select all

$Person = new Me();
$Person->setHeight(6);
$person_height = $Person->getHeight();
PHP5 does have magical get & set methods too - I won't bother explaining them though - do a Google search for "PHP5 __get" or "PHP5 magic functions" if you're interested.