← Back to Chapters

PHP OOP Set Method

? PHP OOP Set Method

? Quick Overview

A setter method in PHP OOP is used to safely assign values to class properties while keeping them protected from direct access.

? Key Concepts

  • Setter methods usually start with set.
  • They control how data is assigned.
  • They protect class properties using encapsulation.

? Syntax / Theory

Setter methods are especially useful when properties are declared as private or protected. They allow validation and rules before assignment.

? Code Example

? View Code Example
// 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();
?>

? Live Output / Explanation

The setter ensures that only valid ages are stored. When setAge(20) is called, the value is accepted and printed using the getter method.

? Interactive Concept

Think of a setter as a security gate: all values must pass validation before entering the class.

? Use Cases

  • Validating user input
  • Applying business rules
  • Protecting sensitive data

✅ Tips & Best Practices

  • Always validate input inside setters.
  • Keep setters focused on a single responsibility.
  • Use getters with setters for full encapsulation.

? Try It Yourself

  • Create a Car class.
  • Add a private property $speed.
  • Write setSpeed() to block negative values.
  • Use getSpeed() to display the value.