How does PHP handle inheritance of private and protected properties in classes?
Private properties in PHP are not inherited by child classes, while protected properties are inherited. To access private properties in child classes, you can use getter and setter methods in the parent class. This way, child classes can indirectly access and modify private properties.
class ParentClass {
private $privateProperty = 'Private Property';
protected $protectedProperty = 'Protected Property';
public function getPrivateProperty() {
return $this->privateProperty;
}
public function setPrivateProperty($value) {
$this->privateProperty = $value;
}
}
class ChildClass extends ParentClass {
public function getProtectedProperty() {
return $this->protectedProperty;
}
}
$parent = new ParentClass();
echo $parent->getPrivateProperty(); // Output: Private Property
$child = new ChildClass();
echo $child->getProtectedProperty(); // Output: Protected Property
Related Questions
- What are some best practices for using array_filter() or array_map() in PHP?
- How can the use of constants in PHP functions impact the execution of the code, especially when using an integrated development environment like Eclipse?
- How can the PHP documentation be effectively utilized to troubleshoot coding issues?