Why would one use a setter when they can simple pass data to a constructor while having the property set as private?
Example:
class recover_password{
private $password;
function __construct($password){
$this->password = $password;
$this->show_pass();
}
function show_pass(){
echo $this->password;
}
}
class recover_password{
private $password;
function set_pass($password){
$this->password = $password;
$this->show_pass();
}
function show_pass(){
echo $this->password;
}
}
//First object
$rec_pass = new recover_password(12345);
//Second object
$rec_pass = new recover_password();
$rec_pass->set_pass(12345);
To answer the broad question in the title first ("What's the point of setters?"):
You use setters as apposed to directly allowing access to properties ($obj->prop = 'foo'
) to have more control over what kind of properties are allowed to be set on the object and when they can be set. A setter, a function, can modify or outright reject a value that you're attempting to set; this is not possible with a simple property assignment.
To answer the question from the code ("Why add a setFoo($foo)
method in addition to/instead of just __construct($foo)
?"):
It depends on what kind of object you want to create. It's absolutely reasonable to have immutable objects which take their data once upon instantiation, and then make it impossible to modify that value. It is also absolutely reasonable to have an object on which you can set a value at any time after its instantiation. Both cases are useful in different situations.
You may even do both at once. Requiring an argument to the constructor ensures that your object always, at all times, will have a particular value. You can then also allow this value to be modified through a setter. Using both together ensures that your object is always in a valid state; i.e. that you can't have an instance of the object without it having a particular value. E.g.:
class Foo {
protected $bar;
public function __construct(Bar $bar) {
$this->bar = $bar;
}
public function setBar(Bar $bar) {
$this->bar = $bar;
}
}
This class is guaranteed to always have a value for $bar
of a valid type (Bar
). You can modify the value as needed, but it's impossible to set invalid values or to not have a value. Leaving out the constructor would mean you could instantiate the class without a Bar
, leaving out the setter would mean you couldn't modify it after instantiation.