Getter and Setter methods

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
timclaason
Forum Commoner
Posts: 77
Joined: Tue Dec 16, 2003 9:06 am
Location: WI

Getter and Setter methods

Post 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.
djot
Forum Contributor
Posts: 313
Joined: Wed Jan 14, 2004 10:21 am
Location: planet earth
Contact:

Post 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
-
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Are you talking about magic methods, or just the concept of getters and setters?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply