Reputation: 3264
I have a class in php and want to know if there is a specific convention how to set these private variables in my constructor.
Should I set them with my setter
or with this
?
class foo {
private $bar;
public function __construct($foobar) {
$this->bar = $foobar;
}
public function setBar($bar) {
$this->bar = $bar;
}
public function getBar() {
return $this->bar;
}
}
OR
class foo {
private $bar;
public function __construct($foobar) {
$this->setBar($foobar);
}
public function setBar($bar) {
$this->bar = $bar;
}
public function getBar() {
return $this->bar;
}
}
Or is my question just philosophical?
Same question could be asked with getters
. But I guess you have to use setters
and getters
when handling private variables of your parent class.
Upvotes: 2
Views: 107
Reputation: 54771
You should use the setBar
in the constructor because of data validation, and future maintenance.
// a developer introduces a bug because the string has padding.
$foo->setBar("chickens ");
// the developer fixes the bug by updating the setBar setter
public function setBar($bar) {
$this->bar = trim($bar);
}
// the developer doesn't see this far away code
$f = new foo("chickens ");
The developer sends the code to production thinking he fixed the bug.
Upvotes: 2
Reputation: 5131
This:
class foo {
private $bar;
public function __construct($foobar) {
$this->bar = $foobar;
}
public function setBar($bar) {
$this->bar = $bar;
}
public function getBar() {
return $this->bar;
}
}
is no different than this:
class foo{
public function __construct($bar){
$this->bar = $bar;
}
public $bar;
One reason to use a getter and a setter is if you only allow a variable to be set on object construction like the following:
class foo {
private $bar;
public function __construct($foobar) {
$this->bar = $foobar;
}
public function getBar() {
return $this->bar;
}
}
So don't overuse getters and setters unless necessary
Upvotes: 1
Reputation: 831
In such a trivial example, yes your question is mostly philosophical! :) However, if your setter would perform some special actions (such like checking the validity of the input, or modifiying it), then I would recommend to use the second scheme.
Upvotes: 1