I wonder this, when should I use getter-setter methods in a class and when should I use class's contruct parameters?
I will explain it with PHP. For example, I write a class below:
class foo{
public $a; //required parameter
public $b; //optional parameter
public function __construct(){
//some code
}
public function setA($a){
$this->a = $a;
}
public function getA(){
return $this->a;
}
public function setB($a){
$this->a = $a;
}
public function getB(){
return $this->a;
}
public function bar(){
//do something with class attributes by using getter - setter methods.
}
}
$foo = new foo();
$foo->setA('something');
$foo->setB('something2');
$foo->bar();
I can write a class by this way absolutely. But, I can write a class another way using construct parameters. Example below:
class foo{
public $a; //required parameter
public $b; //optional parameter
public function __construct($a, $b){
$this->setA($a);
$this->setB($b);
//some code
}
protected function setA($a){
$this->a = $a;
}
public function getA(){
return $this->a;
}
protected function setB($a){
$this->a = $a;
}
public function getB(){
return $this->a;
}
public function bar(){
//do something with class attributes by using getter - setter methods.
}
}
$foo = new foo('something', 'something2');
$foo->bar();
I think that, if I have a required parameter, I want to it on construct method. But, if I have optional parameter, I want it by the setter class. For example:
class foo{
public $a; //required parameter
public $b; //optional parameter
public function __construct($a){
$this->setA($a);
//some code
}
protected function setA($a){
$this->a = $a;
}
public function getA(){
return $this->a;
}
public function setB($a){
$this->a = $a;
}
public function getB(){
return $this->a;
}
public function bar(){
//do something with class attributes by using getter - setter methods.
}
}
$foo = new foo('something');
// if I will use an optional parameter, I can set it by the setter method
$foo->setB('something2');
$foo->bar();
Well, I want to learn stg about code write methods. Which one is popular? Which one is useful, which one is true_ When I should use one of these? Thanks a lot.