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.
Getter and Setter methods
Moderator: General Moderators
-
timclaason
- Forum Commoner
- Posts: 77
- Joined: Tue Dec 16, 2003 9:06 am
- Location: WI
-
perhaps something like this, don't know ...
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();
?>-
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
"Setters" are traditionally functions that set variables in objects, while "Getters" are functions that retrieve those values.
Usage:
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.
Code: Select all
class Me
{
private $height;
function setHeight($feet)
{
$this->height = $feet;
}
function getHeight()
{
return $this->height;
}
}Code: Select all
$Person = new Me();
$Person->setHeight(6);
$person_height = $Person->getHeight();Real programmers don't comment their code. If it was hard to write, it should be hard to understand.