我想知道,什么时候应该在类中使用getter-setter方法,什么时候应该使用类的构造参数?
我将用PHP进行解释。例如,我在下面编写一个类:
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();
我绝对可以用这种方式写一个类。但是,我可以使用构造参数以另一种方式编写类。下面的示例:
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();
我认为,如果我有必需的参数,我想在构造方法上使用它。但是,如果我有可选参数,则需要setter类提供。例如:
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();
嗯,我想学习有关代码编写方法的知识。哪个受欢迎?哪一个有用,哪一个是正确的_什么时候应该使用其中之一?非常感谢。
编写方法和构造函数的“真实”方式取决于实例化时需要的内容。
在构造函数中,必须有所有必需的参数才能使类正常工作,正如您所说的非可选参数。
您还可以在构造函数中插入可选参数,以在此阶段已经知道这些值的情况下简化代码,这样您以后就不必调用其setter。