Is it advisable to have setter methods in subclasses that can modify properties of parent class objects in PHP?
It is generally not advisable to have setter methods in subclasses that directly modify properties of parent class objects in PHP, as this breaks the principle of encapsulation and can lead to unexpected behavior. Instead, it is recommended to use getter and setter methods in the parent class to access and modify its properties, and have the subclasses interact with these methods.
class ParentClass {
protected $property;
public function getProperty() {
return $this->property;
}
public function setProperty($value) {
$this->property = $value;
}
}
class SubClass extends ParentClass {
// Subclass methods
}
// Usage
$parent = new ParentClass();
$parent->setProperty('value');
echo $parent->getProperty(); // Output: value