Ho visto alcuni progetti in cui le classi stanno ottenendo e impostando i metodi per manipolare i dati di inserimento. Dammi un esempio qui:Vale la pena di fare i metodi get e set in OOP?
class Student extends dbClass
{
private $TableID;
private $FullName;
private $Gender;
private $Address;
function setTableID($Value)
{
$this->TableID = $Value;
}
function getTableID()
{
return $this->TableID;
}
function setFullName($Value)
{
$this->FullName = $Value;
}
function getFullName()
{
return $this->FullName;
}
function setGender($Value)
{
$this->Gender = $Value;
}
function getGender()
{
return $this->Gender;
}
function setAddress($Value)
{
$this->Address = $Value;
}
function getAddress()
{
return $this->Address;
}
function UpdateStudent()
{
$sql = "UPDATE INTO usertable SET
FullName = '".$this->getFullName()."',
Gender = '".$this->getGender()."',
Address = '".$this->getAddress()."'
where TableID='".$this->getTableID()."'";
$this->query($sql);
}
}
è al di sopra della classe di esempio che ho visto. E sotto è il processo come lo stanno usando:
$student = new Student;
$student->setTableID = 1;
$student->setFullName('My Name');
$student->setGender('Male');
$student->setAddress('this is my address');
$studen->UpdateStudent();
Vale la pena farlo in questo modo? Personalmente ritengo sia inutile impostare il campo e quindi ottenere e aggiornare i record al suo interno. Ci vuole davvero molto tempo per farlo per ogni modulo. Qual è il modo migliore per gestire questa cosa? C'è qualche problema alla sicurezza in questo modo?
I modificatori di accesso (come 'private') sono spesso interpretati erroneamente come funzionalità di sicurezza. Nella loro attuale incarnazione in C++, essi erano in realtà destinati a limitare l'esposizione ABI (non API); che non è poi così rilevante per PHP e linguaggi di scripting. Richiedere setter e getter è quindi spesso un effetto collaterale, ma non è molto orientato agli oggetti. Vedi anche [PHP Getters and setters: male o male necessario?] (Http://berryllium.nl/2011/02/getters-and-setters-evil-or-necessitive-evil/) e [Java: Getter e setter sono evil] (http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html) – mario
possibile duplicato di [È davvero sbagliato usare non setter e getter?] (http://stackoverflow.com/questions/808348/is-it-really-that-wrong-not-using-setters-and-getters) – mario