How can object properties be overridden and added in a subclass in PHP without cluttering the subclass with unnecessary variables?
When extending a class in PHP, we may want to override or add new properties without cluttering the subclass with unnecessary variables. One way to achieve this is by using the constructor of the subclass to set the overridden or new properties. By doing this, we can keep the subclass clean and organized while still achieving the desired property modifications.
class ParentClass {
public $property1 = 'Parent Property 1';
public $property2 = 'Parent Property 2';
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
$this->property1 = 'Child Property 1'; // overriding property1
$this->property3 = 'Child Property 3'; // adding property3
}
}
$child = new ChildClass();
echo $child->property1; // Output: Child Property 1
echo $child->property2; // Output: Parent Property 2
echo $child->property3; // Output: Child Property 3