Visibility and Constructors
Setter Method
A setter method can validate or normalize a value before storing it.
Setter Method
setter_method.php
<?php
class Thermostat
{
private int $temperature = 70;
public function setTemperature(int $temperature): void
{
$this->temperature = max(50, min(90, $temperature));
}
public function temperature(): int
{
return $this->temperature;
}
}
$target = ;
$thermostat = new Thermostat();
$thermostat->setTemperature($target);
$stored = $thermostat->temperature();
echo "target=" . $target . "\n";
echo "stored=" . $stored . "\n";
<?php
class Thermostat
{
private int $temperature = 70;
public function setTemperature(int $temperature): void
{
$this->temperature = max(50, min(90, $temperature));
}
public function temperature(): int
{
return $this->temperature;
}
}
$target = ;
$thermostat = new Thermostat();
$thermostat->setTemperature($target);
$stored = $thermostat->temperature();
echo "target=" . $target . "\n";
echo "stored=" . $stored . "\n";
<?php
class Thermostat
{
private int $temperature = 70;
public function setTemperature(int $temperature): void
{
$this->temperature = max(50, min(90, $temperature));
}
public function temperature(): int
{
return $this->temperature;
}
}
$target = ;
$thermostat = new Thermostat();
$thermostat->setTemperature($target);
$stored = $thermostat->temperature();
echo "target=" . $target . "\n";
echo "stored=" . $stored . "\n";
controlled write
Setters keep direct writes out of the public API while still allowing updates.