Reputation: 5512
Lets assume I have a class Test, which has got a private attribute called $_list
, and a public setter.
Public setter is used to set the attribute value from the outside.
class Test {
private $_list;
public function getList() {
return $this->_list;
}
public function setList($list) {
$this->_list = $list;
}
public function initialize() {
$list = array();
/* ... Some code that fills the $list with values etc. ... */
// 1) Set value directly
$this->_list = $list;
// 2) Use public setter
$this->setList($list);
}
}
The question is - do I need to use public setter to set private attribute value inside class?
Which way is are better - #1 or #2? And why?
Which way do you prefer?
I would like to see a complete answer with the explaination of advantages and disadvantages of each way.
Thanks.
Upvotes: 3
Views: 668
Reputation: 15758
As it was written above, both are acceptable, but the correct answer is: Rather use the direct attribute access, but sometimes you better use the setters.
Number 1, (property access) Pros:
Number 2, (setter) Pros:
I think that proposing that there is no logic behind using a variable is more important. If it is simple, make it look simple. If it's not, you can still use setters.
You could also ask the same about getters versus property access, the above applies as well.
Upvotes: 1