setter / getter in un metodo
Domanda
Solo un'idea:
esempio (in PHP): per impostare il nome: $ Object > nome ( 'name'); per ottenere il nome: $ Object > Nome ();
Se nessun argomento: il metodo viene utilizzato come getter, altrimenti come setter. Per getter / setter semplici. Stupido, qualunque cosa, forse?
modifica: per dare seguito alle risposte: non mi piace molto ottenere e impostare perché preferisco avere l'interfaccia il più esplicita possibile. Quando ci sono solo alcune proprietà è anche eccessivo IMHO. Quindi vorrei restringerlo a classi / oggetti con un paio di getter / setter espliciti.
Soluzione
Certo, potresti farlo se ha senso nella tua applicazione, altrimenti userei semplicemente i getter / setter standard che sono già stati impostati per te. La tua funzione potrebbe assomigliare a questa:
public function name($val = null)
{
if (is_null($val))
{
return $this->name;
}
else
{
$this->name = $val;
}
}
Altri suggerimenti
Il problema è che sarebbe difficile da seguire. Preferirei di gran lunga usare __get e __set di PHP5, quindi è più naturale ottenere e impostare variabili e tutti saprebbero esattamente cosa sto facendo. IE:
class myClass { function __get($name) { return $this->array[$name]; } function __set($name, $value) { $this->array[$name] = $value; } function print() { echo $this->array['test']; } } $obj = new myClass; $obj->test = "Hi"; echo $obj->test; //echos Hi. $obj->print(); //echos Hi.
Può essere fatto usando il metodo magico __call ().
class Test {
public function __call($name, array $args) {
$variable =& $this->$name;
if(!empty($args)) {
$variable = $args[0];
}
return $variable;
}
}