What is the best practice for handling inheritance and object properties in PHP classes?
When dealing with inheritance and object properties in PHP classes, it is important to use access modifiers (public, protected, private) to control the visibility of properties in parent and child classes. This ensures encapsulation and helps prevent unintended modifications of properties. Additionally, using getters and setters can provide controlled access to object properties and allow for validation or manipulation of data before setting or retrieving values.
class ParentClass {
protected $property;
public function getProperty() {
return $this->property;
}
public function setProperty($value) {
// Add validation or manipulation logic here
$this->property = $value;
}
}
class ChildClass extends ParentClass {
// Child class can access protected property from parent class
}
$child = new ChildClass();
$child->setProperty('new value');
echo $child->getProperty(); // Output: new value