Reputation: 425371
I have a class hierarchy in PHP 5.2.9
.
The base class has a protected property which is an associative array.
The child classes can add some elements to the array.
The child classes are declared in the separate files (plugins), which will be created and added by multiple developers.
Which is the best way to add the elements to the property in the child classes so that declaring a new child would be as simple as possible?
<?php
class A {
protected $myproperty = array (
'A1' => 1,
'A2' => 2
);
function myprint()
{
print_r($this->myproperty);
}
};
class B extends A {
// add 'B1', 'B2' to myproperty
};
class C extends B {
// add 'C1', 'C2' to myproperty
};
$c = new C();
$c->myprint();
// The line above should print A1, A2, B1, B2, C1, C2
?>
Ideally, I'd like to make it for the developers as simple as declaring a variable or a private property, without having a need to copypaste any code.
Upvotes: 4
Views: 1955
Reputation: 37905
Make use of the constructors of the inherited classes, for class B it would become something like this:
class B extends A {
function __construct() {
parent::__construct(); // Call constructor of parent class
array_push($myproperty, "B1", "B2"); // Add our properties
}
}
Same goes for class C.
If you have a lot of inherited classes, or want to provide as much support as possible, you could put this code into some function. So the other developers only need to call this function in their constructor to 'register' their child.
Upvotes: 3