A setter method in PHP OOP is used to safely assign values to class properties while keeping them protected from direct access.
set.Setter methods are especially useful when properties are declared as private or protected. They allow validation and rules before assignment.
// Class demonstrating setter and getter methods
// Setter method with validation
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
} else {
echo "Invalid age";
}
}
// Getter method to access age
public function getAge() {
return $this->age;
}
}
$obj = new Student();
$obj->setAge(20);
echo $obj->getAge();
?>
The setter ensures that only valid ages are stored. When setAge(20) is called, the value is accepted and printed using the getter method.
Think of a setter as a security gate: all values must pass validation before entering the class.
Car class.$speed.setSpeed() to block negative values.getSpeed() to display the value.